use sha2::{Digest, Sha256};
#[inline]
pub fn sha256_hex(input: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(input.as_bytes());
let result = hasher.finalize();
hex::encode(result)
}
#[inline]
pub fn sha256_hex_bytes(input: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(input);
let result = hasher.finalize();
hex::encode(result)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sha256_known_value() {
let h = sha256_hex("abc");
assert_eq!(
h,
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(h.len(), 64);
}
#[test]
fn test_sha256_empty_string() {
let h = sha256_hex("");
assert_eq!(
h,
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
);
}
#[test]
fn test_sha256_is_deterministic() {
let a = sha256_hex("hello world");
let b = sha256_hex("hello world");
assert_eq!(a, b);
}
}