hash_u5.c (1136B)
1 #include "../config.h" 2 #include "ccan/endian/endian.h" 3 #include "ccan/short_types/short_types.h" 4 #include "hash_u5.h" 5 #include <string.h> 6 7 void hash_u5_init(struct hash_u5 *hu5, const char *hrp) 8 { 9 hu5->buf = 0; 10 hu5->num_bits = 0; 11 sha256_init(&hu5->hash); 12 sha256_update(&hu5->hash, hrp, strlen(hrp)); 13 } 14 15 void hash_u5(struct hash_u5 *hu5, const u8 *u5, size_t len) 16 { 17 size_t bits = len * 5; 18 19 while (bits) { 20 size_t n = 5; 21 22 if (bits < n) 23 n = bits; 24 25 hu5->buf <<= n; 26 hu5->buf |= (*u5 >> (5-n)); 27 bits -= n; 28 hu5->num_bits += n; 29 30 if (n == 5) 31 u5++; 32 33 if (hu5->num_bits >= 32) { 34 be32 be32 = cpu_to_be32((u32)(hu5->buf >> (hu5->num_bits-32))); 35 sha256_update(&hu5->hash, &be32, sizeof(be32)); 36 hu5->num_bits -= 32; 37 } 38 } 39 } 40 41 void hash_u5_done(struct hash_u5 *hu5, struct sha256 *res) 42 { 43 if (hu5->num_bits) { 44 be32 be32 = cpu_to_be32((u32)(hu5->buf << (32 - hu5->num_bits))); 45 46 sha256_update(&hu5->hash, &be32, (hu5->num_bits + 7) / 8); 47 } 48 sha256_done(&hu5->hash, res); 49 }