rs_sha256/
sha256hasher.rs

1use crate::{Sha256State, BYTES_LEN};
2use core::hash::Hasher;
3use rs_hasher_ctx::{ByteArrayWrapper, GenericHasher, HasherContext};
4use rs_internal_hasher::HashAlgorithm;
5
6/// `Sha256Hasher` is a type in RustyShield that facilitates the SHA-256 hashing algorithm.
7///
8/// A "Hasher" in cryptographic hashing encapsulates the object managing the transformation of input data into a
9/// fixed-size byte sequence. The Hasher is tasked with maintaining the internal state of the hashing operation,
10/// providing methods to append more data, and retrieve the resulting hash.
11///
12/// The `Sha256Hasher` struct conforms to Rust's `Hasher` trait, enabling interchangeability with other hashers in Rust.
13/// It can be deployed wherever a `Hasher` implementing type is needed.
14///
15/// ## Examples
16///
17/// The following examples illustrate the use of `Sha256Hasher` with both `Hash` and `Hasher`, indicating the source of
18/// the discrepancy:
19///
20///```rust
21/// # use std::hash::{BuildHasher, Hash, Hasher};
22/// # use rs_sha256::Sha256Hasher;
23/// let data = b"hello";
24///
25/// // Using Hash
26/// let mut sha256hasher = Sha256Hasher::default();
27/// data.hash(&mut sha256hasher);
28/// let result_via_hash = sha256hasher.finish();
29///
30/// // Using Hasher
31/// let mut sha256hasher = Sha256Hasher::default();
32/// sha256hasher.write(data);
33/// let result_via_hasher = sha256hasher.finish();
34///
35/// // Simulating the Hash inners
36/// let mut sha256hasher = Sha256Hasher::default();
37/// sha256hasher.write_usize(data.len());
38/// sha256hasher.write(data);
39/// let simulated_hash_result = sha256hasher.finish();
40///
41/// assert_ne!(result_via_hash, result_via_hasher);
42/// assert_eq!(result_via_hash, simulated_hash_result);
43///```
44#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
45pub struct Sha256Hasher(GenericHasher<Sha256State, BYTES_LEN>);
46
47impl From<Sha256Hasher> for Sha256State {
48    fn from(value: Sha256Hasher) -> Self {
49        value.0.state
50    }
51}
52
53impl From<Sha256State> for Sha256Hasher {
54    fn from(value: Sha256State) -> Self {
55        Self(GenericHasher {
56            padding: <Sha256State as HashAlgorithm>::Padding::default(),
57            state: value,
58        })
59    }
60}
61
62impl Hasher for Sha256Hasher {
63    /// Finish the hash and return the hash value as a `u64`.
64    fn finish(&self) -> u64 {
65        self.0.finish()
66    }
67
68    /// Write a byte array to the hasher.
69    /// This hasher can digest up to `u64::MAX` bytes. If more bytes are written, the hasher will panic.
70    fn write(&mut self, bytes: &[u8]) {
71        self.0.write(bytes)
72    }
73}
74
75impl HasherContext<BYTES_LEN> for Sha256Hasher {
76    type Output = ByteArrayWrapper<BYTES_LEN>;
77
78    fn finish(&mut self) -> Self::Output {
79        HasherContext::finish(&mut self.0).into()
80    }
81}