spin_common/
sha256.rs

1//! SHA-256 digest
2
3use std::path::Path;
4
5use sha2::{Digest, Sha256};
6
7/// Return the hex SHA-256 digest of the given bytes.
8pub fn hex_digest_from_bytes(bytes: impl AsRef<[u8]>) -> String {
9    let digest = Sha256::digest(bytes);
10    format!("{digest:x}")
11}
12
13/// Return the hex SHA-256 digest of the given file.
14pub fn hex_digest_from_file(path: impl AsRef<Path>) -> std::io::Result<String> {
15    let mut file = std::fs::File::open(path)?;
16    let mut hasher = sha2::Sha256::new();
17    std::io::copy(&mut file, &mut hasher)?;
18    let digest = hasher.finalize();
19    Ok(format!("{digest:x}"))
20}
21
22#[cfg(test)]
23mod tests {
24    use std::io::Write;
25
26    use super::*;
27
28    #[test]
29    fn test_hex_digest_from_bytes() {
30        let hex = hex_digest_from_bytes("spin");
31        assert_eq!(
32            hex,
33            "a5a2729ffa0eeacc15323a9168807c72d18d1cb375dbde899c44d6803dad2b19"
34        );
35    }
36
37    #[test]
38    fn test_hex_digest_from_file() {
39        let mut f = tempfile::NamedTempFile::new().unwrap();
40        write!(&mut f, "spin").unwrap();
41        let hex = hex_digest_from_file(f.into_temp_path()).unwrap();
42        assert_eq!(
43            hex,
44            "a5a2729ffa0eeacc15323a9168807c72d18d1cb375dbde899c44d6803dad2b19"
45        );
46    }
47}