Skip to main content

edda_core/
hash.rs

1use sha2::{Digest, Sha256};
2
3/// Compute SHA-256 hash of bytes, returning lowercase hex string.
4pub fn sha256_hex(bytes: &[u8]) -> String {
5    let mut hasher = Sha256::new();
6    hasher.update(bytes);
7    hex::encode(hasher.finalize())
8}
9
10#[cfg(test)]
11mod tests {
12    use super::*;
13
14    #[test]
15    fn sha256_empty() {
16        let h = sha256_hex(b"");
17        assert_eq!(
18            h,
19            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
20        );
21    }
22
23    #[test]
24    fn sha256_hello() {
25        let h = sha256_hex(b"hello");
26        assert_eq!(
27            h,
28            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
29        );
30    }
31
32    #[test]
33    fn output_is_64_char_lowercase_hex() {
34        let h = sha256_hex(b"test");
35        assert_eq!(h.len(), 64);
36        assert!(h
37            .chars()
38            .all(|c| c.is_ascii_hexdigit() && !c.is_uppercase()));
39    }
40}