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