Skip to main content

quantaegis_drbg/
hmac.rs

1//! **NIST FIPS 198-1 HMAC-SHA-256** keyed-hash message authentication code.
2//!
3//! Shared primitive for both SP 800-90A Rev. 1 `HMAC_DRBG(SHA-256)` and FIPS 140-3
4//! software integrity verification. Per FIPS 140-3 IG 10.2.A, [`HmacSha256::self_test`]
5//! MUST execute before any integrity verification that relies on this implementation.
6
7use core::fmt;
8
9use quantaegis_core::ct::{Choice, ct_eq_slice};
10use quantaegis_core::{Error, Result, SecretBytes, Zeroize};
11
12use crate::sha256::Sha256;
13
14/// Streaming **HMAC-SHA-256** authentication context (`FIPS 198-1, Section 4`).
15///
16/// Key-derived inner and outer hash states are automatically zeroized on drop. To avoid moving
17/// key-derived hash states across stack frames, callers in FIPS boundary code should create an
18/// [`HmacSha256::uninitialized`] slot and initialize it in place via [`HmacSha256::init_into`],
19/// or use [`HmacSha256::mac_into`] / [`HmacSha256::mac_chunks_into`].
20pub struct HmacSha256 {
21    inner: Sha256,
22    outer: Sha256,
23    finalized: bool,
24}
25
26impl HmacSha256 {
27    /// Output tag length in bytes (`32` bytes / `256` bits).
28    pub const TAG_LEN: usize = Sha256::DIGEST_LEN;
29
30    /// Underlying hash block length in bytes (`64` bytes).
31    pub const BLOCK_LEN: usize = Sha256::BLOCK_LEN;
32
33    /// Creates an uninitialized HMAC-SHA-256 slot that rejects updates and finalization until
34    /// initialized in place via [`Self::init_into`].
35    #[inline]
36    pub const fn uninitialized() -> Self {
37        Self {
38            inner: Sha256::new(),
39            outer: Sha256::new(),
40            finalized: true,
41        }
42    }
43
44    /// Initializes `self` in place with `key`, avoiding by-value stack moves of key-derived
45    /// `ipad`/`opad` hash states.
46    ///
47    /// Keys longer than 64 bytes are hashed directly into a zeroized stack buffer per FIPS 198-1
48    /// Table 1 Step 2; shorter keys (including 0-byte keys for non-approved low-level testing)
49    /// are zero-padded to 64 bytes. Approved-mode minimum key length policies (`>= 112` bits) are
50    /// enforced by the FIPS module boundary layer.
51    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    /// Initializes a new HMAC-SHA-256 context with `key`.
79    ///
80    /// For FIPS boundary code handling secret keys, prefer [`Self::uninitialized`] +
81    /// [`Self::init_into`] or [`Self::mac_into`] to initialize states in their resting place.
82    pub fn new(key: &[u8]) -> Self {
83        let mut ctx = Self::uninitialized();
84        ctx.init_into(key);
85        ctx
86    }
87
88    /// Absorbs `data` into the inner HMAC hash, rejecting uninitialized or finalized contexts.
89    #[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    /// Absorbs `data` into the inner HMAC hash.
98    #[inline]
99    pub fn update(&mut self, data: &[u8]) {
100        let _ = self.try_update(data);
101    }
102
103    /// Finalizes the authentication tag directly into `out`, zeroizes internal states, and marks
104    /// the context finalized until [`Self::init_into`] is called again.
105    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    /// Finalizes the authentication tag directly into `out` and zeroizes internal states.
119    ///
120    /// If uninitialized or already finalized, zeroes `out`.
121    #[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    /// Finalizes the HMAC context and returns the 32-byte tag.
129    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    /// Computes `HMAC-SHA-256(key, data)` directly into `out` without moving key states or tag.
136    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    /// Computes `HMAC-SHA-256(key, chunks[0] || chunks[1] || ...)` directly into `out`.
141    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    /// Computes `HMAC-SHA-256(key, data)` in one shot.
151    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    /// Computes `HMAC-SHA-256(key, chunks[0] || chunks[1] || ...)` in one shot.
158    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    /// Computes `HMAC-SHA-256(key, data)` directly into zeroized storage and compares against
165    /// `expected_tag` in constant time.
166    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    /// Executes the FIPS 140-3 known-answer self-test (CAST) for HMAC-SHA-256.
173    ///
174    /// Covers both a **256-bit (32-byte) approved-strength key** (meeting FIPS 140-3's minimum
175    /// approved key-length requirement for pre-integrity HMAC CAST) and a **131-byte key**
176    /// exceeding the 64-byte block size (RFC 4231 Test Case 6) in constant time.
177    ///
178    /// Per FIPS 140-3 IG 10.2.A, this CAST MUST succeed before running any software integrity
179    /// check that relies on `HmacSha256`.
180    pub fn self_test() -> Result<()> {
181        // 32-byte (256-bit) approved key KAT (independently verified against Python hmac/hashlib).
182        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        // RFC 4231 Test Case 6 (131-byte key > 64-byte block size).
194        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        // Independent Python reference values for 0 B, 64 B, and 65 B keys.
261        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        // Uninitialized and post-finalize contexts reject updates and finalization.
278        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}