1#include "hash.h"
2#include "hash_ctxt.h"
3
4#include "system.h"
5
6const SHA256_DIGEST SHA256_ZEROED = {.data: {0}};
7
8static void digest_str(const unsigned char *digest, size_t digest_len, char *str, size_t max_len)
9{
10 if(max_len > digest_len * 2 + 1)
11 {
12 max_len = digest_len * 2 + 1;
13 }
14 str[max_len - 1] = 0;
15 max_len -= 1;
16 for(size_t i = 0; i < max_len; i++)
17 {
18 static const char HEX[] = "0123456789abcdef";
19 size_t index = i / 2;
20 if(i % 2 == 0)
21 {
22 str[i] = HEX[digest[index] >> 4];
23 }
24 else
25 {
26 str[i] = HEX[digest[index] & 0xf];
27 }
28 }
29}
30
31SHA256_DIGEST sha256(const void *message, size_t message_len)
32{
33 SHA256_CTX ctxt;
34 sha256_init(ctxt: &ctxt);
35 sha256_update(ctxt: &ctxt, data: message, data_len: message_len);
36 return sha256_finish(ctxt: &ctxt);
37}
38
39void sha256_str(SHA256_DIGEST digest, char *str, size_t max_len)
40{
41 digest_str(digest: digest.data, digest_len: sizeof(digest.data), str, max_len);
42}
43
44int sha256_from_str(SHA256_DIGEST *out, const char *str)
45{
46 return str_hex_decode(dst: out->data, dst_size: sizeof(out->data), src: str);
47}
48
49int sha256_comp(SHA256_DIGEST digest1, SHA256_DIGEST digest2)
50{
51 return mem_comp(a: digest1.data, b: digest2.data, size: sizeof(digest1.data));
52}
53
54MD5_DIGEST md5(const void *message, size_t message_len)
55{
56 MD5_CTX ctxt;
57 md5_init(ctxt: &ctxt);
58 md5_update(ctxt: &ctxt, data: message, data_len: message_len);
59 return md5_finish(ctxt: &ctxt);
60}
61
62void md5_str(MD5_DIGEST digest, char *str, size_t max_len)
63{
64 digest_str(digest: digest.data, digest_len: sizeof(digest.data), str, max_len);
65}
66
67int md5_from_str(MD5_DIGEST *out, const char *str)
68{
69 return str_hex_decode(dst: out->data, dst_size: sizeof(out->data), src: str);
70}
71
72int md5_comp(MD5_DIGEST digest1, MD5_DIGEST digest2)
73{
74 return mem_comp(a: digest1.data, b: digest2.data, size: sizeof(digest1.data));
75}
76