commonware_cryptography/sha256/
mod.rs

1//! SHA-256 implementation of the `Hasher` trait.
2//!
3//! This implementation uses the `sha2` crate to generate SHA-256 digests.
4//!
5//! # Example
6//! ```rust
7//! use commonware_cryptography::{Hasher, Sha256};
8//!
9//! // Create a new SHA-256 hasher
10//! let mut hasher = Sha256::new();
11//!
12//! // Update the hasher with some messages
13//! hasher.update(b"hello,");
14//! hasher.update(b"world!");
15//!
16//! // Finalize the hasher to get the digest
17//! let digest = hasher.finalize();
18//!
19//! // Print the digest
20//! println!("digest: {:?}", digest);
21//! ```
22
23use crate::Hasher;
24use bytes::{Buf, BufMut};
25use commonware_codec::{Error as CodecError, FixedSize, Read, ReadExt, Write};
26use commonware_utils::{hex, Array};
27use rand::{CryptoRng, Rng};
28use sha2::{Digest as _, Sha256 as ISha256};
29use std::{
30    fmt::{Debug, Display},
31    ops::Deref,
32};
33
34const DIGEST_LENGTH: usize = 32;
35
36/// Generate a SHA-256 digest from a message.
37pub fn hash(message: &[u8]) -> Digest {
38    let array: [u8; DIGEST_LENGTH] = ISha256::digest(message).into();
39    Digest::from(array)
40}
41
42/// SHA-256 hasher.
43#[derive(Debug)]
44pub struct Sha256 {
45    hasher: ISha256,
46}
47
48impl Default for Sha256 {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl Clone for Sha256 {
55    fn clone(&self) -> Self {
56        // We manually implement `Clone` to avoid cloning the hasher state.
57        Self::default()
58    }
59}
60
61impl Hasher for Sha256 {
62    type Digest = Digest;
63
64    fn new() -> Self {
65        Self {
66            hasher: ISha256::new(),
67        }
68    }
69
70    fn update(&mut self, message: &[u8]) {
71        self.hasher.update(message);
72    }
73
74    fn finalize(&mut self) -> Self::Digest {
75        let finalized = self.hasher.finalize_reset();
76        let array: [u8; DIGEST_LENGTH] = finalized.into();
77        Self::Digest::from(array)
78    }
79
80    fn reset(&mut self) {
81        self.hasher = ISha256::new();
82    }
83
84    fn random<R: Rng + CryptoRng>(rng: &mut R) -> Self::Digest {
85        let mut digest = [0u8; DIGEST_LENGTH];
86        rng.fill_bytes(&mut digest);
87        Self::Digest::from(digest)
88    }
89}
90
91/// Digest of a SHA-256 hashing operation.
92#[derive(Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
93#[repr(transparent)]
94pub struct Digest([u8; DIGEST_LENGTH]);
95
96impl Write for Digest {
97    fn write(&self, buf: &mut impl BufMut) {
98        self.0.write(buf);
99    }
100}
101
102impl Read for Digest {
103    fn read_cfg(buf: &mut impl Buf, _: &()) -> Result<Self, CodecError> {
104        let array = <[u8; DIGEST_LENGTH]>::read(buf)?;
105        Ok(Self(array))
106    }
107}
108
109impl FixedSize for Digest {
110    const SIZE: usize = DIGEST_LENGTH;
111}
112
113impl Array for Digest {}
114
115impl From<[u8; DIGEST_LENGTH]> for Digest {
116    fn from(value: [u8; DIGEST_LENGTH]) -> Self {
117        Self(value)
118    }
119}
120
121impl AsRef<[u8]> for Digest {
122    fn as_ref(&self) -> &[u8] {
123        &self.0
124    }
125}
126
127impl Deref for Digest {
128    type Target = [u8];
129    fn deref(&self) -> &[u8] {
130        &self.0
131    }
132}
133
134impl Debug for Digest {
135    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
136        write!(f, "{}", hex(&self.0))
137    }
138}
139
140impl Display for Digest {
141    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
142        write!(f, "{}", hex(&self.0))
143    }
144}
145
146impl crate::Digest for Digest {}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151    use commonware_codec::{DecodeExt, Encode};
152    use commonware_utils::hex;
153
154    const HELLO_DIGEST: &str = "b94d27b9934d3e08a52e52d7da7dabfac484efe37a5380ee9088f7ace2efcde9";
155
156    #[test]
157    fn test_sha256() {
158        let msg = b"hello world";
159
160        // Generate initial hash
161        let mut hasher = Sha256::new();
162        hasher.update(msg);
163        let digest = hasher.finalize();
164        assert!(Digest::decode(digest.as_ref()).is_ok());
165        assert_eq!(hex(digest.as_ref()), HELLO_DIGEST);
166
167        // Reuse hasher
168        hasher.update(msg);
169        let digest = hasher.finalize();
170        assert!(Digest::decode(digest.as_ref()).is_ok());
171        assert_eq!(hex(digest.as_ref()), HELLO_DIGEST);
172
173        // Test simple hasher
174        let hash = hash(msg);
175        assert_eq!(hex(hash.as_ref()), HELLO_DIGEST);
176    }
177
178    #[test]
179    fn test_sha256_len() {
180        assert_eq!(Digest::SIZE, DIGEST_LENGTH);
181    }
182
183    #[test]
184    fn test_codec() {
185        let msg = b"hello world";
186        let mut hasher = Sha256::new();
187        hasher.update(msg);
188        let digest = hasher.finalize();
189
190        let encoded = digest.encode();
191        assert_eq!(encoded.len(), DIGEST_LENGTH);
192        assert_eq!(encoded, digest.as_ref());
193
194        let decoded = Digest::decode(encoded).unwrap();
195        assert_eq!(digest, decoded);
196    }
197}