1pub fn blake2b_256(input: &[u8], output: &mut [u8; 32]) {
19 use ::blake2::digest::{
20 consts::U32,
21 Digest as _,
22 };
23
24 type Blake2b256 = ::blake2::Blake2b<U32>;
25
26 let mut blake2 = Blake2b256::new();
27 blake2.update(input);
28 let result = blake2.finalize();
29 output.copy_from_slice(&result);
30}
31
32pub fn blake2b_128(input: &[u8], output: &mut [u8; 16]) {
34 use ::blake2::digest::{
35 consts::U16,
36 Digest as _,
37 };
38
39 type Blake2b128 = ::blake2::Blake2b<U16>;
40
41 let mut blake2 = Blake2b128::new();
42 blake2.update(input);
43 let result = blake2.finalize();
44 output.copy_from_slice(&result);
45}
46
47pub fn keccak_256(input: &[u8], output: &mut [u8; 32]) {
49 use sha3::{
50 digest::generic_array::GenericArray,
51 Digest as _,
52 };
53 let mut hasher = sha3::Keccak256::new();
54 hasher.update(input);
55 hasher.finalize_into(<&mut GenericArray<u8, _>>::from(&mut output[..]));
56}
57
58pub fn sha2_256(input: &[u8], output: &mut [u8; 32]) {
60 use sha2::{
61 digest::generic_array::GenericArray,
62 Digest as _,
63 };
64 let mut hasher = sha2::Sha256::new();
65 hasher.update(input);
66 hasher.finalize_into(<&mut GenericArray<u8, _>>::from(&mut output[..]));
67}
68
69#[cfg(test)]
70mod tests {
71 use super::*;
72
73 static TEST_INPUT: &[u8] = b"DEAD_BEEF";
74
75 #[test]
76 fn test_hash_keccak_256() {
77 let mut output = [0x00_u8; 32];
78 keccak_256(TEST_INPUT, &mut output);
79 assert_eq!(
80 output,
81 [
82 24, 230, 209, 59, 127, 30, 158, 244, 60, 177, 132, 150, 167, 244, 64, 69,
83 184, 123, 185, 44, 211, 199, 208, 179, 14, 64, 126, 140, 217, 69, 36,
84 216
85 ]
86 );
87 }
88
89 #[test]
90 fn test_hash_sha2_256() {
91 let mut output = [0x00_u8; 32];
92 sha2_256(TEST_INPUT, &mut output);
93 assert_eq!(
94 output,
95 [
96 136, 15, 25, 218, 88, 54, 49, 152, 115, 168, 147, 189, 207, 171, 243,
97 129, 161, 76, 15, 141, 197, 106, 111, 213, 19, 197, 133, 219, 181, 233,
98 195, 120
99 ]
100 );
101 }
102
103 #[test]
104 fn test_hash_blake2_256() {
105 let mut output = [0x00_u8; 32];
106 blake2b_256(TEST_INPUT, &mut output);
107 assert_eq!(
108 output,
109 [
110 244, 247, 235, 182, 194, 161, 28, 69, 34, 106, 237, 7, 57, 87, 190, 12,
111 92, 171, 91, 176, 135, 52, 247, 94, 8, 112, 94, 183, 140, 101, 208, 120
112 ]
113 );
114 }
115
116 #[test]
117 fn test_hash_blake2_128() {
118 let mut output = [0x00_u8; 16];
119 blake2b_128(TEST_INPUT, &mut output);
120 assert_eq!(
121 output,
122 [
123 180, 158, 48, 21, 171, 163, 217, 175, 145, 160, 25, 159, 213, 142, 103,
124 242
125 ]
126 );
127 }
128}