| 1 | #ifndef BASE_HASH_H |
| 2 | #define BASE_HASH_H |
| 3 | |
| 4 | #include <cstddef> // size_t |
| 5 | |
| 6 | static constexpr size_t SHA256_DIGEST_LENGTH = 256 / 8; |
| 7 | static constexpr size_t SHA256_MAXSTRSIZE = 2 * SHA256_DIGEST_LENGTH + 1; |
| 8 | static constexpr size_t MD5_DIGEST_LENGTH = 128 / 8; |
| 9 | static constexpr size_t MD5_MAXSTRSIZE = 2 * MD5_DIGEST_LENGTH + 1; |
| 10 | |
| 11 | struct SHA256_DIGEST |
| 12 | { |
| 13 | unsigned char data[SHA256_DIGEST_LENGTH]; |
| 14 | }; |
| 15 | |
| 16 | struct MD5_DIGEST |
| 17 | { |
| 18 | unsigned char data[MD5_DIGEST_LENGTH]; |
| 19 | }; |
| 20 | |
| 21 | SHA256_DIGEST sha256(const void *message, size_t message_len); |
| 22 | void sha256_str(SHA256_DIGEST digest, char *str, size_t max_len); |
| 23 | int sha256_from_str(SHA256_DIGEST *out, const char *str); |
| 24 | int sha256_comp(SHA256_DIGEST digest1, SHA256_DIGEST digest2); |
| 25 | |
| 26 | MD5_DIGEST md5(const void *message, size_t message_len); |
| 27 | void md5_str(MD5_DIGEST digest, char *str, size_t max_len); |
| 28 | int md5_from_str(MD5_DIGEST *out, const char *str); |
| 29 | int md5_comp(MD5_DIGEST digest1, MD5_DIGEST digest2); |
| 30 | |
| 31 | inline bool operator==(const SHA256_DIGEST &that, const SHA256_DIGEST &other) |
| 32 | { |
| 33 | return sha256_comp(digest1: that, digest2: other) == 0; |
| 34 | } |
| 35 | inline bool operator!=(const SHA256_DIGEST &that, const SHA256_DIGEST &other) |
| 36 | { |
| 37 | return !(that == other); |
| 38 | } |
| 39 | inline bool operator==(const MD5_DIGEST &that, const MD5_DIGEST &other) |
| 40 | { |
| 41 | return md5_comp(digest1: that, digest2: other) == 0; |
| 42 | } |
| 43 | inline bool operator!=(const MD5_DIGEST &that, const MD5_DIGEST &other) |
| 44 | { |
| 45 | return !(that == other); |
| 46 | } |
| 47 | |
| 48 | #endif // BASE_HASH_H |
| 49 | |