1use crate::{permutation::State, Error};
2
3struct Sponge {
4 state: State,
5 pos: usize,
6}
7
8impl Sponge {
9 fn new(iv: u64) -> Self {
10 let mut state = State([iv, 0, 0, 0, 0]);
11 state.permute(12);
12 Self { state, pos: 0 }
13 }
14
15 fn update(&mut self, input: &[u8]) {
16 for &byte in input {
17 self.state.xor_byte(self.pos, byte);
18 self.pos += 1;
19 if self.pos == 8 {
20 self.state.permute(12);
21 self.pos = 0;
22 }
23 }
24 }
25
26 fn pad(&mut self) {
27 self.state.xor_byte(self.pos, 1);
28 self.state.permute(12);
29 self.pos = 0;
30 }
31
32 fn finalize(mut self) -> XofReader {
33 self.pad();
34 XofReader {
35 state: self.state,
36 pos: 0,
37 }
38 }
39}
40
41pub struct Hash256(Sponge);
43
44impl Default for Hash256 {
45 fn default() -> Self {
46 Self::new()
47 }
48}
49
50impl Hash256 {
51 pub fn new() -> Self {
53 Self(Sponge::new(0x0000080100cc0002))
54 }
55 pub fn update(&mut self, input: &[u8]) {
57 self.0.update(input);
58 }
59 pub fn finalize(self) -> [u8; 32] {
61 let mut output = [0; 32];
62 self.0.finalize().read(&mut output);
63 output
64 }
65}
66
67pub struct Xof128(Sponge);
69
70impl Default for Xof128 {
71 fn default() -> Self {
72 Self::new()
73 }
74}
75
76impl Xof128 {
77 pub fn new() -> Self {
79 Self(Sponge::new(0x0000080000cc0003))
80 }
81 pub fn update(&mut self, input: &[u8]) {
83 self.0.update(input);
84 }
85 pub fn finalize(self) -> XofReader {
87 self.0.finalize()
88 }
89}
90
91pub struct Cxof128(Sponge);
93
94impl Cxof128 {
95 pub fn new(customization: &[u8]) -> Result<Self, Error> {
98 if customization.len() > 256 {
99 return Err(Error::CustomizationTooLong);
100 }
101 let mut sponge = Sponge::new(0x0000080000cc0004);
102 sponge.update(&((customization.len() as u64) * 8).to_le_bytes());
103 sponge.update(customization);
104 sponge.pad();
105 Ok(Self(sponge))
106 }
107 pub fn update(&mut self, input: &[u8]) {
109 self.0.update(input);
110 }
111 pub fn finalize(self) -> XofReader {
113 self.0.finalize()
114 }
115}
116
117pub struct XofReader {
119 state: State,
120 pos: usize,
121}
122
123impl XofReader {
124 pub fn read(&mut self, output: &mut [u8]) {
126 for byte in output {
127 if self.pos == 8 {
128 self.state.permute(12);
129 self.pos = 0;
130 }
131 *byte = self.state.byte(self.pos);
132 self.pos += 1;
133 }
134 }
135}
136
137pub fn hash256(message: &[u8]) -> [u8; 32] {
139 let mut hash = Hash256::new();
140 hash.update(message);
141 hash.finalize()
142}
143
144pub fn xof128(message: &[u8], output: &mut [u8]) {
146 let mut xof = Xof128::new();
147 xof.update(message);
148 xof.finalize().read(output);
149}
150
151pub fn cxof128(message: &[u8], customization: &[u8], output: &mut [u8]) -> Result<(), Error> {
154 let mut xof = Cxof128::new(customization)?;
155 xof.update(message);
156 xof.finalize().read(output);
157 Ok(())
158}