1use core::fmt;
8
9use quantaegis_core::ct::{Choice, ct_eq_slice};
10use quantaegis_core::{Error, Result, SecretBytes, Zeroize};
11
12use crate::sha256::Sha256;
13
14pub struct HmacSha256 {
21 inner: Sha256,
22 outer: Sha256,
23 finalized: bool,
24}
25
26impl HmacSha256 {
27 pub const TAG_LEN: usize = Sha256::DIGEST_LEN;
29
30 pub const BLOCK_LEN: usize = Sha256::BLOCK_LEN;
32
33 #[inline]
36 pub const fn uninitialized() -> Self {
37 Self {
38 inner: Sha256::new(),
39 outer: Sha256::new(),
40 finalized: true,
41 }
42 }
43
44 pub fn init_into(&mut self, key: &[u8]) {
52 self.zeroize();
53
54 let mut key_block = SecretBytes::new([0u8; Self::BLOCK_LEN]);
55 if key.len() > Self::BLOCK_LEN {
56 let mut hashed = SecretBytes::new([0u8; Self::TAG_LEN]);
57 Sha256::digest_into(key, hashed.expose_secret_mut());
58 key_block.expose_secret_mut()[..Self::TAG_LEN].copy_from_slice(hashed.expose_secret());
59 } else {
60 key_block.expose_secret_mut()[..key.len()].copy_from_slice(key);
61 }
62
63 let mut ipad = SecretBytes::new([0x36u8; Self::BLOCK_LEN]);
64 let mut opad = SecretBytes::new([0x5cu8; Self::BLOCK_LEN]);
65 for i in 0..Self::BLOCK_LEN {
66 let kb = key_block.expose_secret()[i];
67 ipad.expose_secret_mut()[i] ^= kb;
68 opad.expose_secret_mut()[i] ^= kb;
69 }
70
71 self.inner.reset();
72 self.inner.update(ipad.expose_secret());
73 self.outer.reset();
74 self.outer.update(opad.expose_secret());
75 self.finalized = false;
76 }
77
78 pub fn new(key: &[u8]) -> Self {
83 let mut ctx = Self::uninitialized();
84 ctx.init_into(key);
85 ctx
86 }
87
88 #[inline]
90 pub fn try_update(&mut self, data: &[u8]) -> Result<()> {
91 if self.finalized {
92 return Err(Error::DrbgInvalidRequest);
93 }
94 self.inner.try_update(data)
95 }
96
97 #[inline]
99 pub fn update(&mut self, data: &[u8]) {
100 let _ = self.try_update(data);
101 }
102
103 pub fn try_finalize_into(&mut self, out: &mut [u8; Self::TAG_LEN]) -> Result<()> {
106 if self.finalized {
107 return Err(Error::DrbgInvalidRequest);
108 }
109 let mut inner_digest = SecretBytes::new([0u8; Self::TAG_LEN]);
110 self.inner
111 .try_finalize_into(inner_digest.expose_secret_mut())?;
112 self.outer.try_update(inner_digest.expose_secret())?;
113 self.outer.try_finalize_into(out)?;
114 self.finalized = true;
115 Ok(())
116 }
117
118 #[inline]
122 pub fn finalize_into(&mut self, out: &mut [u8; Self::TAG_LEN]) {
123 if self.try_finalize_into(out).is_err() {
124 out.zeroize();
125 }
126 }
127
128 pub fn finalize(mut self) -> [u8; Self::TAG_LEN] {
130 let mut out = [0u8; Self::TAG_LEN];
131 self.finalize_into(&mut out);
132 out
133 }
134
135 pub fn mac_into(key: &[u8], data: &[u8], out: &mut [u8; Self::TAG_LEN]) {
137 Self::mac_chunks_into(key, &[data], out);
138 }
139
140 pub fn mac_chunks_into(key: &[u8], chunks: &[&[u8]], out: &mut [u8; Self::TAG_LEN]) {
142 let mut ctx = Self::uninitialized();
143 ctx.init_into(key);
144 for &chunk in chunks {
145 ctx.update(chunk);
146 }
147 ctx.finalize_into(out);
148 }
149
150 pub fn mac(key: &[u8], data: &[u8]) -> [u8; Self::TAG_LEN] {
152 let mut out = [0u8; Self::TAG_LEN];
153 Self::mac_into(key, data, &mut out);
154 out
155 }
156
157 pub fn mac_chunks(key: &[u8], chunks: &[&[u8]]) -> [u8; Self::TAG_LEN] {
159 let mut out = [0u8; Self::TAG_LEN];
160 Self::mac_chunks_into(key, chunks, &mut out);
161 out
162 }
163
164 pub fn verify(key: &[u8], data: &[u8], expected_tag: &[u8; Self::TAG_LEN]) -> Choice {
167 let mut computed = SecretBytes::new([0u8; Self::TAG_LEN]);
168 Self::mac_into(key, data, computed.expose_secret_mut());
169 ct_eq_slice(computed.expose_secret(), expected_tag)
170 }
171
172 pub fn self_test() -> Result<()> {
181 const KEY_32B: [u8; 32] = [
183 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d,
184 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b,
185 0x2c, 0x2d, 0x2e, 0x2f,
186 ];
187 const MSG_32B: &[u8] = b"quantaegis-fips-hmac-sha256-cast-v1";
188 const EXPECTED_32B: [u8; 32] = [
189 0xb2, 0x96, 0xd1, 0xc0, 0x7a, 0xc8, 0x37, 0xf5, 0xe5, 0xf6, 0x83, 0x2a, 0xf6, 0xdf,
190 0x45, 0x3b, 0x99, 0x3f, 0x6a, 0xd2, 0x13, 0x2e, 0x77, 0xf7, 0xc5, 0x71, 0x59, 0x6c,
191 0x4c, 0x0b, 0x98, 0xc5,
192 ];
193 const EXPECTED_TC6: [u8; 32] = [
195 0x60, 0xe4, 0x31, 0x59, 0x1e, 0xe0, 0xb6, 0x7f, 0x0d, 0x8a, 0x26, 0xaa, 0xcb, 0xf5,
196 0xb7, 0x7f, 0x8e, 0x0b, 0xc6, 0x21, 0x37, 0x28, 0xc5, 0x14, 0x05, 0x46, 0x04, 0x0f,
197 0x0e, 0xe3, 0x7f, 0x54,
198 ];
199
200 let mut t1 = [0u8; Self::TAG_LEN];
201 Self::mac_into(&KEY_32B, MSG_32B, &mut t1);
202
203 let long_key = [0xaau8; 131];
204 let mut t6 = [0u8; Self::TAG_LEN];
205 Self::mac_into(
206 &long_key,
207 b"Test Using Larger Than Block-Size Key - Hash Key First",
208 &mut t6,
209 );
210
211 let ok = ct_eq_slice(&t1, &EXPECTED_32B) & ct_eq_slice(&t6, &EXPECTED_TC6);
212 if ok.into_bool() {
213 Ok(())
214 } else {
215 Err(Error::SelfTestFailed)
216 }
217 }
218}
219
220impl Zeroize for HmacSha256 {
221 #[inline]
222 fn zeroize(&mut self) {
223 self.inner.zeroize();
224 self.outer.zeroize();
225 self.finalized = true;
226 }
227}
228
229impl Drop for HmacSha256 {
230 #[inline]
231 fn drop(&mut self) {
232 self.zeroize();
233 }
234}
235
236impl fmt::Debug for HmacSha256 {
237 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
238 f.write_str("HmacSha256([REDACTED])")
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 fn to_hex(bytes: &[u8; 32]) -> [u8; 64] {
247 const HEX: &[u8; 16] = b"0123456789abcdef";
248 let mut out = [0u8; 64];
249 for (i, &b) in bytes.iter().enumerate() {
250 out[2 * i] = HEX[usize::from(b >> 4)];
251 out[2 * i + 1] = HEX[usize::from(b & 0x0f)];
252 }
253 out
254 }
255
256 #[test]
257 fn hmac_sha256_self_test_key_boundaries_and_lifecycle() {
258 assert_eq!(HmacSha256::self_test(), Ok(()));
259
260 let t0 = HmacSha256::mac(b"", b"abc");
262 assert_eq!(
263 &to_hex(&t0)[..],
264 b"fd7adb152c05ef80dccf50a1fa4c05d5a3ec6da95575fc312ae7c5d091836351"
265 );
266 let t64 = HmacSha256::mac(&[0x42u8; 64], b"abc");
267 assert_eq!(
268 &to_hex(&t64)[..],
269 b"50f0e0ea48e489e346ef8a73ee3054aec3bd4a48b35f3462c60fb5238071027c"
270 );
271 let t65 = HmacSha256::mac(&[0x42u8; 65], b"abc");
272 assert_eq!(
273 &to_hex(&t65)[..],
274 b"6cd602fe782b1354cb4ac34e0d625cfd2ea0dcefdae7ebb6b0977e3d729bc9f0"
275 );
276
277 let mut ctx = HmacSha256::uninitialized();
279 let mut out = [0xEEu8; 32];
280 assert_eq!(ctx.try_update(b"abc"), Err(Error::DrbgInvalidRequest));
281 assert_eq!(
282 ctx.try_finalize_into(&mut out),
283 Err(Error::DrbgInvalidRequest)
284 );
285 assert_eq!(out, [0xEEu8; 32]);
286
287 ctx.init_into(&[0x42u8; 64]);
288 assert_eq!(ctx.try_update(b"a"), Ok(()));
289 assert_eq!(ctx.try_update(b"bc"), Ok(()));
290 assert_eq!(ctx.try_finalize_into(&mut out), Ok(()));
291 assert_eq!(out, t64);
292 assert_eq!(ctx.try_update(b"more"), Err(Error::DrbgInvalidRequest));
293 assert_eq!(
294 ctx.try_finalize_into(&mut out),
295 Err(Error::DrbgInvalidRequest)
296 );
297
298 assert!(HmacSha256::verify(&[0x42u8; 64], b"abc", &t64).into_bool());
299 let mut bad = t64;
300 bad[0] ^= 0x01;
301 assert!(!HmacSha256::verify(&[0x42u8; 64], b"abc", &bad).into_bool());
302 }
303}