Skip to main content

ghpascon_rust/utils/
hash.rs

1use sha2::{Digest, Sha256};
2
3/// Returns the SHA-256 hex digest of the given string.
4pub fn get_hash(data: &str) -> String {
5    let mut hasher = Sha256::new();
6    hasher.update(data.as_bytes());
7    hex::encode(hasher.finalize())
8}
9
10#[cfg(test)]
11mod tests {
12    use super::*;
13
14    #[test]
15    fn test_known_hash() {
16        // echo -n "hello" | sha256sum
17        assert_eq!(
18            get_hash("hello"),
19            "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"
20        );
21    }
22
23    #[test]
24    fn test_empty_string() {
25        assert_eq!(
26            get_hash(""),
27            "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
28        );
29    }
30
31    #[test]
32    fn test_deterministic() {
33        assert_eq!(get_hash("rust"), get_hash("rust"));
34    }
35}