tiny_keccak/keccak.rs
1//! The `Keccak` hash functions.
2
3use super::{bits_to_rate, keccakf::KeccakF, Hasher, KeccakState};
4
5/// The `Keccak` hash functions defined in [`Keccak SHA3 submission`].
6///
7/// # Usage
8///
9/// ```toml
10/// [dependencies]
11/// tiny-keccak = { version = "2.0.0", features = ["keccak"] }
12/// ```
13///
14/// [`Keccak SHA3 submission`]: https://keccak.team/files/Keccak-submission-3.pdf
15#[derive(Clone)]
16pub struct Keccak {
17 state: KeccakState<KeccakF>,
18}
19
20impl Keccak {
21 const DELIM: u8 = 0x01;
22
23 /// Creates new [`Keccak`] hasher with a security level of 224 bits.
24 ///
25 /// [`Keccak`]: struct.Keccak.html
26 pub fn v224() -> Keccak {
27 Keccak::new(224)
28 }
29
30 /// Creates new [`Keccak`] hasher with a security level of 256 bits.
31 ///
32 /// [`Keccak`]: struct.Keccak.html
33 pub fn v256() -> Keccak {
34 Keccak::new(256)
35 }
36
37 /// Creates new [`Keccak`] hasher with a security level of 384 bits.
38 ///
39 /// [`Keccak`]: struct.Keccak.html
40 pub fn v384() -> Keccak {
41 Keccak::new(384)
42 }
43
44 /// Creates new [`Keccak`] hasher with a security level of 512 bits.
45 ///
46 /// [`Keccak`]: struct.Keccak.html
47 pub fn v512() -> Keccak {
48 Keccak::new(512)
49 }
50
51 fn new(bits: usize) -> Keccak {
52 Keccak {
53 state: KeccakState::new(bits_to_rate(bits), Self::DELIM),
54 }
55 }
56}
57
58impl Hasher for Keccak {
59 /// Absorb additional input. Can be called multiple times.
60 ///
61 /// # Example
62 ///
63 /// ```
64 /// # use tiny_keccak::{Hasher, Keccak};
65 /// #
66 /// # fn main() {
67 /// # let mut keccak = Keccak::v256();
68 /// keccak.update(b"hello");
69 /// keccak.update(b" world");
70 /// # }
71 /// ```
72 fn update(&mut self, input: &[u8]) {
73 self.state.update(input);
74 }
75
76 /// Pad and squeeze the state to the output.
77 ///
78 /// # Example
79 ///
80 /// ```
81 /// # use tiny_keccak::{Hasher, Keccak};
82 /// #
83 /// # fn main() {
84 /// # let keccak = Keccak::v256();
85 /// # let mut output = [0u8; 32];
86 /// keccak.finalize(&mut output);
87 /// # }
88 /// #
89 /// ```
90 fn finalize(self, output: &mut [u8]) {
91 self.state.finalize(output);
92 }
93}