Skip to main content

hashtree_core/
hash.rs

1//! Hashing utilities using SHA256
2
3use crate::types::Hash;
4use sha2::{Digest, Sha256};
5
6/// Compute SHA256 hash of data
7pub fn sha256(data: &[u8]) -> Hash {
8    let mut hasher = Sha256::new();
9    hasher.update(data);
10    let result = hasher.finalize();
11    let mut hash = [0u8; 32];
12    hash.copy_from_slice(&result);
13    hash
14}
15
16/// Verify that data matches expected hash
17pub fn verify(hash: &Hash, data: &[u8]) -> bool {
18    let computed = sha256(data);
19    computed == *hash
20}
21
22#[cfg(test)]
23mod tests {
24    use super::*;
25    use crate::types::to_hex;
26
27    #[test]
28    fn test_sha256_empty() {
29        let hash = sha256(&[]);
30        assert_eq!(
31            to_hex(&hash),
32            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
33        );
34    }
35
36    #[test]
37    fn test_sha256_hello_world() {
38        let data = b"hello world";
39        let hash = sha256(data);
40        assert_eq!(
41            to_hex(&hash),
42            "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9"
43        );
44    }
45
46    #[test]
47    fn test_sha256_consistent() {
48        let data = [1u8, 2, 3, 4, 5];
49        let hash1 = sha256(&data);
50        let hash2 = sha256(&data);
51        assert_eq!(to_hex(&hash1), to_hex(&hash2));
52    }
53
54    #[test]
55    fn test_sha256_length() {
56        let data = [1u8, 2, 3];
57        let hash = sha256(&data);
58        assert_eq!(hash.len(), 32);
59    }
60
61    #[test]
62    fn test_verify() {
63        let data = b"test data";
64        let hash = sha256(data);
65        assert!(verify(&hash, data));
66        assert!(!verify(&hash, b"different data"));
67    }
68}