sha1.ha (1276B)
1 // SPDX-License-Identifier: MPL-2.0 2 // (c) Hare authors <https://harelang.org> 3 4 use bytes; 5 use crypto::mac; 6 use crypto::sha1; 7 use hash; 8 use io; 9 10 export type sha1state = struct { 11 mac::mac, 12 h: sha1::state, 13 keypad: [sha1::BLOCKSZ]u8, 14 }; 15 16 const sha1_vtable: io::vtable = io::vtable { 17 writer = &sha1write, 18 ... 19 }; 20 21 // Creates a [[crypto::mac::mac]] that computes an HMAC with given 'key' using 22 // SHA1 as underlying hash function. 23 // 24 // The caller must take extra care to call [[crypto::mac::finish]] when they are 25 // finished using the MAC function, which, in addition to freeing state 26 // associated with the MAC, will securely erase state which contains secret 27 // information. 28 export fn sha1(key: []u8) sha1state = { 29 let s = sha1state { 30 h = sha1::sha1(), 31 stream = &sha1_vtable, 32 sz = sha1::SZ, 33 bsz = sha1::BLOCKSZ, 34 sum = &sha1sum, 35 finish = &sha1finish, 36 ... 37 }; 38 39 init(&s.h, key, s.keypad); 40 return s; 41 }; 42 43 fn sha1write(st: *io::stream, buf: const []u8) (size | io::error) = { 44 let hm = st: *sha1state; 45 return hash::write(&hm.h, buf); 46 }; 47 48 fn sha1sum(mac: *mac::mac, dest: []u8) void = { 49 let hm = mac: *sha1state; 50 sum(&hm.h, hm.keypad, dest); 51 }; 52 53 fn sha1finish(mac: *mac::mac) void = { 54 let hm = mac: *sha1state; 55 bytes::zero(hm.keypad); 56 io::close(&hm.h)!; 57 };