Skip to main content

dryoc/
sha256.rs

1//! # SHA-256 hash algorithm
2//!
3//! Provides an implementation of the SHA-256 hash algorithm.
4//!
5//! SHA-256 is an unkeyed cryptographic hash function. It turns arbitrary input
6//! bytes into a 32-byte digest. Hashes are useful for fingerprints and
7//! compatibility with protocols that require SHA-256, but they do not
8//! authenticate messages by themselves. Use [`crate::auth`] or [`crate::hmac`]
9//! when a secret key must be involved.
10//!
11//! ## Example
12//!
13//! ```
14//! use dryoc::sha256::Sha256;
15//!
16//! let mut state = Sha256::new();
17//! state.update(b"All the world's a stage, ");
18//! state.update(b"and all the men and women merely players.");
19//! let hash = state.finalize_to_vec();
20//! assert_eq!(hash.len(), 32);
21//! ```
22use sha2::{Digest as DigestImpl, Sha256 as Sha256Impl};
23
24use crate::constants::CRYPTO_HASH_SHA256_BYTES;
25use crate::types::*;
26
27/// Type alias for SHA256 digest, provided for convenience.
28pub type Digest = StackByteArray<CRYPTO_HASH_SHA256_BYTES>;
29
30/// SHA-256 wrapper, provided for convenience.
31pub struct Sha256 {
32    hasher: Sha256Impl,
33}
34
35impl Sha256 {
36    /// Returns a new SHA-256 hasher instance.
37    pub fn new() -> Self {
38        Self {
39            hasher: Sha256Impl::new(),
40        }
41    }
42
43    /// One-time interface to compute SHA-256 digest for `input`, copying result
44    /// into `output`.
45    pub fn compute_into_bytes<
46        Input: Bytes + ?Sized,
47        Output: MutByteArray<CRYPTO_HASH_SHA256_BYTES>,
48    >(
49        output: &mut Output,
50        input: &Input,
51    ) {
52        let mut hasher = Self::new();
53        hasher.update(input);
54        hasher.finalize_into_bytes(output)
55    }
56
57    /// One-time interface to compute SHA-256 digest for `input`.
58    pub fn compute<Input: Bytes + ?Sized, Output: NewByteArray<CRYPTO_HASH_SHA256_BYTES>>(
59        input: &Input,
60    ) -> Output {
61        let mut hasher = Self::new();
62        hasher.update(input);
63        hasher.finalize()
64    }
65
66    /// Wrapper around [`Sha256::compute`], returning a [`Vec`]. Provided for
67    /// convenience.
68    pub fn compute_to_vec<Input: Bytes + ?Sized>(input: &Input) -> Vec<u8> {
69        Self::compute(input)
70    }
71
72    /// Updates SHA-256 hash state with `input`.
73    pub fn update<Input: Bytes + ?Sized>(&mut self, input: &Input) {
74        self.hasher.update(input.as_slice())
75    }
76
77    /// Consumes hasher and return final computed hash.
78    pub fn finalize<Output: NewByteArray<CRYPTO_HASH_SHA256_BYTES>>(self) -> Output {
79        let mut hash = Output::new_byte_array();
80        self.finalize_into_bytes(&mut hash);
81        hash
82    }
83
84    /// Consumes hasher and writes final computed hash into `output`.
85    pub fn finalize_into_bytes<Output: MutByteArray<CRYPTO_HASH_SHA256_BYTES>>(
86        self,
87        output: &mut Output,
88    ) {
89        let digest = self.hasher.finalize();
90        output.as_mut_slice().copy_from_slice(&digest);
91    }
92
93    /// Consumes hasher and returns final computed hash as a [`Vec`].
94    pub fn finalize_to_vec(self) -> Vec<u8> {
95        self.finalize()
96    }
97}
98
99impl Default for Sha256 {
100    fn default() -> Self {
101        Self::new()
102    }
103}
104
105#[cfg(test)]
106mod tests {
107    use super::*;
108
109    #[test]
110    fn test_sha256_known_answer() {
111        let digest = Sha256::compute_to_vec(b"abc");
112        assert_eq!(
113            digest,
114            hex::decode("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad")
115                .expect("hex failed")
116        );
117    }
118}