ssi_crypto/hashes/
sha256.rs

1//! Cryptographic hash functions
2//!
3//! The [`sha256`] function requires feature either `sha2` or `ring` (not both).
4
5/// SHA-256 hash
6pub fn sha256(data: &[u8]) -> [u8; 32] {
7    #[cfg(feature = "ring")]
8    {
9        // The "ring" feature takes precedence for the impl of sha256.
10        use ring::digest;
11        let hash = digest::digest(&digest::SHA256, data);
12
13        // we're pretty sure this will always be 32 bytes long
14        assert!(
15            hash.as_ref().len() == digest::SHA256.output_len,
16            "ring's Sha256 implementation has returned a digest of len {}, expected 32",
17            hash.as_ref().len()
18        );
19
20        hash.as_ref().try_into().unwrap()
21    }
22    #[cfg(not(feature = "ring"))]
23    {
24        // Only if "ring" is not enabled, but "sha2" is, does it use "sha2" for the sha256 impl.
25        use sha2::Digest;
26        let mut hasher = sha2::Sha256::new();
27        hasher.update(data);
28        hasher.finalize().into()
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use super::*;
35
36    #[test]
37    fn sha256_empty() {
38        assert_eq!(
39            sha256(&[]),
40            [
41                227, 176, 196, 66, 152, 252, 28, 20, 154, 251, 244, 200, 153, 111, 185, 36, 39,
42                174, 65, 228, 100, 155, 147, 76, 164, 149, 153, 27, 120, 82, 184, 85
43            ]
44        );
45    }
46}