dryoc/classic/
crypto_hash.rs1use crate::constants::CRYPTO_HASH_SHA512_BYTES;
2use crate::sha512::*;
3
4pub type Digest = [u8; CRYPTO_HASH_SHA512_BYTES];
6
7pub fn crypto_hash_sha512(output: &mut Digest, input: &[u8]) {
9 let mut state = crypto_hash_sha512_init();
10 crypto_hash_sha512_update(&mut state, input);
11 crypto_hash_sha512_final(state, output);
12}
13
14#[derive(Default)]
16pub struct Sha512State {
17 pub(super) hasher: Sha512,
18}
19
20pub fn crypto_hash_sha512_init() -> Sha512State {
22 Sha512State::default()
23}
24
25pub fn crypto_hash_sha512_update(state: &mut Sha512State, input: &[u8]) {
27 state.hasher.update(input);
28}
29
30pub fn crypto_hash_sha512_final(state: Sha512State, output: &mut Digest) {
33 state.hasher.finalize_into_bytes(output)
34}
35
36#[cfg(test)]
37mod tests {
38 use super::*;
39
40 #[test]
41 fn test_crypto_hash_sha512() {
42 use sodiumoxide::crypto::hash;
43
44 use crate::rng::randombytes_buf;
45
46 let r = randombytes_buf(64);
47
48 let their_digest = hash::hash(&r);
49 let mut our_digest = [0u8; CRYPTO_HASH_SHA512_BYTES];
50 crypto_hash_sha512(&mut our_digest, &r);
51
52 assert_eq!(their_digest.as_ref(), our_digest);
53 }
54
55 #[test]
56 fn test_crypto_hash_sha512_update() {
57 use sodiumoxide::crypto::hash;
58
59 use crate::rng::randombytes_buf;
60
61 let mut their_state = hash::State::new();
62 let mut our_state = crypto_hash_sha512_init();
63
64 for _ in 0..10 {
65 let r = randombytes_buf(64);
66 their_state.update(&r);
67 crypto_hash_sha512_update(&mut our_state, &r);
68 }
69
70 let their_digest = their_state.finalize();
71 let mut our_digest = [0u8; CRYPTO_HASH_SHA512_BYTES];
72 crypto_hash_sha512_final(our_state, &mut our_digest);
73
74 assert_eq!(their_digest.as_ref(), our_digest);
75 }
76}