tiny_keccak/
sha3.rs

1use crate::{bits_to_rate, keccakf::KeccakF, Hasher, KeccakState};
2
3/// The `SHA3` hash functions defined in [`FIPS-202`].
4///
5/// [`FIPS-202`]: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.202.pdf
6///
7/// # Usage
8///
9/// ```toml
10/// [dependencies]
11/// tiny-keccak = { version = "2.0.0", features = ["sha3"] }
12/// ```
13///
14/// # Example
15///
16/// ```
17/// # use tiny_keccak::{Hasher, Sha3};
18/// #
19/// # fn main() {
20/// let input = b"hello world";
21/// let mut output = [0; 32];
22/// let expected = b"\
23///     \x64\x4b\xcc\x7e\x56\x43\x73\x04\x09\x99\xaa\xc8\x9e\x76\x22\xf3\
24///     \xca\x71\xfb\xa1\xd9\x72\xfd\x94\xa3\x1c\x3b\xfb\xf2\x4e\x39\x38\
25/// ";
26/// let mut sha3 = Sha3::v256();
27/// sha3.update(input);
28/// sha3.finalize(&mut output);
29/// assert_eq!(expected, &output);
30/// # }
31/// ```
32#[derive(Clone)]
33pub struct Sha3 {
34    state: KeccakState<KeccakF>,
35}
36
37impl Sha3 {
38    const DELIM: u8 = 0x06;
39
40    /// Creates  new [`Sha3`] hasher with a security level of 224 bits.
41    ///
42    /// [`Sha3`]: struct.Sha3.html
43    pub fn v224() -> Sha3 {
44        Sha3::new(224)
45    }
46
47    /// Creates  new [`Sha3`] hasher with a security level of 256 bits.
48    ///
49    /// [`Sha3`]: struct.Sha3.html
50    pub fn v256() -> Sha3 {
51        Sha3::new(256)
52    }
53
54    /// Creates  new [`Sha3`] hasher with a security level of 384 bits.
55    ///
56    /// [`Sha3`]: struct.Sha3.html
57    pub fn v384() -> Sha3 {
58        Sha3::new(384)
59    }
60
61    /// Creates  new [`Sha3`] hasher with a security level of 512 bits.
62    ///
63    /// [`Sha3`]: struct.Sha3.html
64    pub fn v512() -> Sha3 {
65        Sha3::new(512)
66    }
67
68    fn new(bits: usize) -> Sha3 {
69        Sha3 {
70            state: KeccakState::new(bits_to_rate(bits), Self::DELIM),
71        }
72    }
73}
74
75impl Hasher for Sha3 {
76    fn update(&mut self, input: &[u8]) {
77        self.state.update(input);
78    }
79
80    fn finalize(self, output: &mut [u8]) {
81        self.state.finalize(output);
82    }
83}