openMSX
sha1.hh
Go to the documentation of this file.
1#ifndef SHA1_HH
2#define SHA1_HH
3
4#include "xrange.hh"
5#include <array>
6#include <cstdint>
7#include <ostream>
8#include <span>
9#include <string>
10#include <string_view>
11
12namespace openmsx {
13
23{
24public:
27
28 // note: default copy and assign are ok
29 Sha1Sum();
31 explicit Sha1Sum(std::string_view hex);
32
37 void parse40(std::span<const char, 40> str);
38 [[nodiscard]] std::string toString() const;
39
40 // Test or set 'null' value.
41 [[nodiscard]] bool empty() const;
42 void clear();
43
44 // gcc-10.2 miscompiles this (fixed in gcc-11),
45 // so still manually implement operator==.
46 //[[nodiscard]] constexpr bool operator==(const Sha1Sum&) const = default;
47 [[nodiscard]] bool operator==(const Sha1Sum& other) const {
48 for (int i : xrange(5)) {
49 if (a[i] != other.a[i]) return false;
50 }
51 return true;
52 }
53 [[nodiscard]] constexpr auto operator<=>(const Sha1Sum& other) const {
54 for (int i : xrange(5 - 1)) {
55 if (auto cmp = a[i] <=> other.a[i]; cmp != 0) return cmp;
56 }
57 return a[5 - 1] <=> other.a[5 - 1];
58 }
59
60 friend std::ostream& operator<<(std::ostream& os, const Sha1Sum& sum) {
61 os << sum.toString();
62 return os;
63 }
64
65private:
66 std::array<uint32_t, 5> a;
67 friend class SHA1;
68};
69
70
79class SHA1
80{
81public:
82 SHA1();
83
85 void update(std::span<const uint8_t> data);
86
89 [[nodiscard]] Sha1Sum digest();
90
92 [[nodiscard]] static Sha1Sum calc(std::span<const uint8_t> data);
93
94private:
95 void transform(std::span<const uint8_t, 64> buffer);
96 void finalize();
97
98private:
99 uint64_t m_count = 0; // in bytes (sha1 reference implementation counts in bits)
100 Sha1Sum m_state;
101 std::array<uint8_t, 64> m_buffer;
102 bool m_finalized = false;
103};
104
105} // namespace openmsx
106
107#endif
Helper class to perform a sha1 calculation.
Definition sha1.hh:80
Sha1Sum digest()
Get the final hash.
void update(std::span< const uint8_t > data)
Incrementally calculate the hash value.
static Sha1Sum calc(std::span< const uint8_t > data)
Easier to use interface, if you can pass all data in one go.
This class represents the result of a sha1 calculation (a 160-bit value).
Definition sha1.hh:23
bool operator==(const Sha1Sum &other) const
Definition sha1.hh:47
Sha1Sum(UninitializedTag)
Definition sha1.hh:26
bool empty() const
void parse40(std::span< const char, 40 > str)
Parse from a 40-character long buffer.
constexpr auto operator<=>(const Sha1Sum &other) const
Definition sha1.hh:53
friend std::ostream & operator<<(std::ostream &os, const Sha1Sum &sum)
Definition sha1.hh:60
std::string toString() const
This file implemented 3 utility functions:
Definition Autofire.cc:9
auto sum(InputRange &&range, Proj proj={})
Definition stl.hh:245
constexpr auto xrange(T e)
Definition xrange.hh:132