Skip to main content

quantaegis_drbg/
hmac_drbg.rs

1//! **NIST SP 800-90A Rev. 1 `HMAC_DRBG(SHA-256)`** with **SP 800-90C** reseed-budget enforcement.
2//!
3//! Implements SP 800-90A Rev. 1 Section 10.1.2 (`HMAC_DRBG_Update`, `HMAC_DRBG_Instantiate`,
4//! `HMAC_DRBG_Reseed`, `HMAC_DRBG_Generate`) and Section 11.3 health-check KATs in pure `#![no_std]`
5//! Rust with zero external dependencies and zero heap allocation.
6//!
7//! # SP 800-90A / SP 800-90C Alignment
8//! - For 256-bit security strength (`RBG2`), initialization requires at least **384 bits (48 bytes)**
9//!   of min-entropy ([`HmacDrbgSha256::instantiate_rbg2_in_place`]) or `>= 32` bytes entropy plus a
10//!   `>= 16` byte nonce satisfying SP 800-90A Section 8.6.7 uniqueness/entropy requirements
11//!   ([`HmacDrbgSha256::instantiate_in_place`]).
12//! - Reseeding requires at least **256 bits (32 bytes)** of fresh min-entropy.
13//! - After emitting **`2^17` bits (16,384 bytes)** since the last instantiation or reseed, the DRBG
14//!   returns [`Error::DrbgReseedRequired`] before any subsequent `generate` call until reseeded
15//!   (SP 800-90C §§5.2.3–5.3). A single request crossing the threshold completes (up to
16//!   `MAX_BYTES_PER_REQUEST`), and the following `generate` call requires a reseed first.
17//! - Zero-byte `generate` requests follow SP 800-90A §10.1.2.5: they still check preconditions,
18//!   reseed when prediction resistance is enabled, advance `(K, V)` via backtracking-resistant
19//!   `Update`, and increment `reseed_counter`.
20//! - Once [`Zeroize::zeroize`] is called, the instance transitions to the uninitialized state and
21//!   rejects all `generate`, `generate_with_prediction_resistance`, and `reseed` calls until
22//!   explicitly re-instantiated in place.
23
24use core::fmt;
25
26use quantaegis_core::ct::ct_eq_slice;
27use quantaegis_core::{Error, Result, Zeroize};
28
29use crate::hmac::HmacSha256;
30
31/// NIST SP 800-90A Rev. 1 `HMAC_DRBG(SHA-256)` state (`K`, `V`, counters, lifecycle flag).
32///
33/// All internal secret state (`key`, `val`, counters) is automatically zeroized on drop.
34/// For FIPS module boundaries, prefer [`Self::uninitialized`] combined with
35/// [`Self::instantiate_in_place`] or [`Self::instantiate_rbg2_in_place`] so `(K, V)` are
36/// initialized directly in their final resting place without by-value stack moves.
37pub struct HmacDrbgSha256 {
38    key: [u8; Self::OUT_LEN],
39    val: [u8; Self::OUT_LEN],
40    reseed_counter: u64,
41    bytes_since_reseed: u64,
42    prediction_resistance: bool,
43    initialized: bool,
44}
45
46impl HmacDrbgSha256 {
47    /// Maximum supported DRBG security strength in bits (`256`, SP 800-90A Rev. 1 Table 2).
48    pub const SECURITY_STRENGTH_BITS: usize = 256;
49
50    /// Underlying HMAC-SHA-256 output block size in bytes (`32`).
51    pub const OUT_LEN: usize = HmacSha256::TAG_LEN;
52
53    /// Minimum entropy input length in bytes (`32` bytes / `256` bits, SP 800-90A Rev. 1 Table 2).
54    pub const MIN_ENTROPY_LEN: usize = 32;
55
56    /// Minimum nonce length in bytes (`16` bytes / `128` bits, SP 800-90A Rev. 1 Section 8.6.7).
57    pub const MIN_NONCE_LEN: usize = 16;
58
59    /// Minimum initialization min-entropy in bytes for 256-bit RBG2 (`48` bytes / `384` bits,
60    /// SP 800-90C Section 5.2.3).
61    pub const RBG2_INIT_MIN_ENTROPY_LEN: usize = 48;
62
63    /// Maximum output length per single `generate` request (`65,536` bytes = `2^19` bits,
64    /// SP 800-90A Rev. 1 Table 2).
65    pub const MAX_BYTES_PER_REQUEST: usize = 65_536;
66
67    /// Maximum `reseed_counter` before a reseed is mandatory (`2^48`, SP 800-90A Rev. 1 Table 2).
68    pub const MAX_RESEED_INTERVAL: u64 = 1u64 << 48;
69
70    /// SP 800-90C Sections 5.2.3–5.3 output threshold (`16,384` bytes = `2^17` bits): once total
71    /// output since instantiation or last reseed reaches this threshold, the next `generate` call
72    /// requires a reseed first.
73    pub const SP800_90C_RESEED_BYTES: u64 = 16_384;
74
75    /// Maximum length in bytes accepted for any single input (`entropy`, `nonce`,
76    /// `personalization`, or `additional_input`), safely below the SP 800-90A `2^35`-bit ceiling.
77    pub const MAX_INPUT_LEN: usize = 1 << 30;
78
79    /// Creates an uninitialized DRBG slot (`initialized == false`).
80    ///
81    /// All `generate`, `generate_with_prediction_resistance`, and `reseed` calls fail with
82    /// [`Error::DrbgInvalidRequest`] until [`Self::instantiate_in_place`] or
83    /// [`Self::instantiate_rbg2_in_place`] succeeds.
84    #[inline]
85    pub const fn uninitialized() -> Self {
86        Self {
87            key: [0u8; Self::OUT_LEN],
88            val: [0u8; Self::OUT_LEN],
89            reseed_counter: 0,
90            bytes_since_reseed: 0,
91            prediction_resistance: false,
92            initialized: false,
93        }
94    }
95
96    /// Instantiates `self` **in place** (`SP 800-90A Rev. 1, Section 10.1.2.3`), avoiding
97    /// by-value stack moves of `(K, V)`.
98    ///
99    /// Enforces:
100    /// - `entropy.len() >= 32` (256 bits)
101    /// - `nonce.len() >= 16` (128 bits; caller MUST guarantee SP 800-90A §8.6.7 nonce uniqueness
102    ///   or `>= 128` bits of min-entropy so the nonce does not repeat across instantiations)
103    /// - each input `<= MAX_INPUT_LEN`
104    ///
105    /// On error, `self` is left zeroized and uninitialized.
106    pub fn instantiate_in_place(
107        &mut self,
108        entropy: &[u8],
109        nonce: &[u8],
110        personalization: &[u8],
111        prediction_resistance: bool,
112    ) -> Result<()> {
113        self.zeroize();
114        if entropy.len() < Self::MIN_ENTROPY_LEN
115            || nonce.len() < Self::MIN_NONCE_LEN
116            || entropy.len() > Self::MAX_INPUT_LEN
117            || nonce.len() > Self::MAX_INPUT_LEN
118            || personalization.len() > Self::MAX_INPUT_LEN
119        {
120            return Err(Error::DrbgInvalidRequest);
121        }
122
123        self.key.fill(0x00);
124        self.val.fill(0x01);
125        self.update(&[entropy, nonce, personalization]);
126        self.reseed_counter = 1;
127        self.bytes_since_reseed = 0;
128        self.prediction_resistance = prediction_resistance;
129        self.initialized = true;
130        Ok(())
131    }
132
133    /// Instantiates `self` **in place** for a 256-bit **SP 800-90C RBG2** construction.
134    ///
135    /// Requires at least **384 bits (48 bytes)** of min-entropy in `entropy` (combining the
136    /// 256-bit security strength and 128-bit nonce entropy per SP 800-90C §5.2.3).
137    /// On error, `self` is left zeroized and uninitialized.
138    pub fn instantiate_rbg2_in_place(
139        &mut self,
140        entropy: &[u8],
141        personalization: &[u8],
142        prediction_resistance: bool,
143    ) -> Result<()> {
144        self.zeroize();
145        if entropy.len() < Self::RBG2_INIT_MIN_ENTROPY_LEN
146            || entropy.len() > Self::MAX_INPUT_LEN
147            || personalization.len() > Self::MAX_INPUT_LEN
148        {
149            return Err(Error::DrbgInvalidRequest);
150        }
151
152        self.key.fill(0x00);
153        self.val.fill(0x01);
154        self.update(&[entropy, personalization]);
155        self.reseed_counter = 1;
156        self.bytes_since_reseed = 0;
157        self.prediction_resistance = prediction_resistance;
158        self.initialized = true;
159        Ok(())
160    }
161
162    /// Convenience constructor delegating to [`Self::instantiate_in_place`].
163    ///
164    /// Prefer [`Self::uninitialized`] + [`Self::instantiate_in_place`] in FIPS boundary code to
165    /// initialize `(K, V)` directly in their final storage without a `Result<Self>` stack move.
166    pub fn instantiate(
167        entropy: &[u8],
168        nonce: &[u8],
169        personalization: &[u8],
170        prediction_resistance: bool,
171    ) -> Result<Self> {
172        let mut drbg = Self::uninitialized();
173        drbg.instantiate_in_place(entropy, nonce, personalization, prediction_resistance)?;
174        Ok(drbg)
175    }
176
177    /// Convenience constructor delegating to [`Self::instantiate_rbg2_in_place`].
178    ///
179    /// Prefer [`Self::uninitialized`] + [`Self::instantiate_rbg2_in_place`] in FIPS boundary code.
180    pub fn instantiate_rbg2(
181        entropy: &[u8],
182        personalization: &[u8],
183        prediction_resistance: bool,
184    ) -> Result<Self> {
185        let mut drbg = Self::uninitialized();
186        drbg.instantiate_rbg2_in_place(entropy, personalization, prediction_resistance)?;
187        Ok(drbg)
188    }
189
190    /// Reseeds an initialized DRBG with at least **256 bits (32 bytes)** of fresh entropy
191    /// (`SP 800-90A Rev. 1, Section 10.1.2.4`).
192    ///
193    /// Returns [`Error::DrbgInvalidRequest`] if the DRBG is uninitialized/zeroized or inputs
194    /// violate length bounds.
195    pub fn reseed(&mut self, entropy: &[u8], additional_input: &[u8]) -> Result<()> {
196        if !self.initialized
197            || entropy.len() < Self::MIN_ENTROPY_LEN
198            || entropy.len() > Self::MAX_INPUT_LEN
199            || additional_input.len() > Self::MAX_INPUT_LEN
200        {
201            return Err(Error::DrbgInvalidRequest);
202        }
203
204        self.update(&[entropy, additional_input]);
205        self.reseed_counter = 1;
206        self.bytes_since_reseed = 0;
207        Ok(())
208    }
209
210    /// Generates pseudorandom bytes into `out` (`SP 800-90A Rev. 1, Section 10.1.2.5`).
211    ///
212    /// On any error, `out` is left unmodified:
213    /// - [`Error::DrbgInvalidRequest`] if uninitialized/zeroized or `out.len() > MAX_BYTES_PER_REQUEST`
214    ///   or `additional_input.len() > MAX_INPUT_LEN`.
215    /// - [`Error::DrbgReseedRequired`] if configured with `prediction_resistance == true`,
216    ///   `reseed_counter > MAX_RESEED_INTERVAL`, or `bytes_since_reseed >= SP800_90C_RESEED_BYTES`.
217    ///
218    /// Note: a 0-byte `out` slice still executes SP 800-90A §10.1.2.5 state update and increments
219    /// `reseed_counter` without emitting bytes.
220    pub fn generate(&mut self, out: &mut [u8], additional_input: &[u8]) -> Result<()> {
221        if !self.initialized {
222            return Err(Error::DrbgInvalidRequest);
223        }
224        if self.prediction_resistance || self.needs_reseed() {
225            return Err(Error::DrbgReseedRequired);
226        }
227        if out.len() > Self::MAX_BYTES_PER_REQUEST || additional_input.len() > Self::MAX_INPUT_LEN {
228            return Err(Error::DrbgInvalidRequest);
229        }
230        self.generate_inner(out, additional_input);
231        Ok(())
232    }
233
234    /// Reseeds an initialized DRBG with fresh `entropy` and generates pseudorandom bytes into
235    /// `out` (`SP 800-90A Rev. 1, Section 9.3.1` with prediction resistance).
236    ///
237    /// Per SP 800-90A Rev. 1 Section 9.3.1 Step 5, returns [`Error::DrbgInvalidRequest`] without
238    /// modifying state or `out` if `prediction_resistance == false` on this instance, if the DRBG
239    /// is uninitialized/zeroized, or if length bounds are violated. Note: a 0-byte `out` slice
240    /// still reseeds and advances internal state per SP 800-90A §9.3.1.
241    pub fn generate_with_prediction_resistance(
242        &mut self,
243        out: &mut [u8],
244        entropy: &[u8],
245        additional_input: &[u8],
246    ) -> Result<()> {
247        if !self.initialized
248            || !self.prediction_resistance
249            || out.len() > Self::MAX_BYTES_PER_REQUEST
250            || entropy.len() < Self::MIN_ENTROPY_LEN
251            || entropy.len() > Self::MAX_INPUT_LEN
252            || additional_input.len() > Self::MAX_INPUT_LEN
253        {
254            return Err(Error::DrbgInvalidRequest);
255        }
256
257        // SP 800-90A §9.3.1 Step 7: reseed with (entropy_input, additional_input), then
258        // generate with empty additional_input.
259        self.reseed(entropy, additional_input)?;
260        self.generate_inner(out, &[]);
261        Ok(())
262    }
263
264    /// Returns `true` if this DRBG is currently instantiated and usable.
265    #[inline]
266    pub const fn is_initialized(&self) -> bool {
267        self.initialized
268    }
269
270    /// Returns the current SP 800-90A `reseed_counter`.
271    #[inline]
272    pub const fn reseed_counter(&self) -> u64 {
273        self.reseed_counter
274    }
275
276    /// Returns the cumulative number of bytes generated since instantiation or the last reseed.
277    #[inline]
278    pub const fn bytes_since_reseed(&self) -> u64 {
279        self.bytes_since_reseed
280    }
281
282    /// Returns `true` if the DRBG is uninitialized or must be reseeded before calling
283    /// [`Self::generate`].
284    #[inline]
285    pub const fn needs_reseed(&self) -> bool {
286        !self.initialized
287            || self.reseed_counter > Self::MAX_RESEED_INTERVAL
288            || self.bytes_since_reseed >= Self::SP800_90C_RESEED_BYTES
289    }
290
291    /// Returns whether this instance enforces prediction resistance on every generate call.
292    #[inline]
293    pub const fn prediction_resistance(&self) -> bool {
294        self.prediction_resistance
295    }
296
297    /// SP 800-90A Rev. 1 Section 10.1.2.2 `HMAC_DRBG_Update(provided_data, K, V)`.
298    ///
299    /// Reuses a single in-place [`HmacSha256`] slot without allocating or moving key-derived states.
300    fn update(&mut self, provided_chunks: &[&[u8]]) {
301        let has_data = provided_chunks.iter().any(|c| !c.is_empty());
302        let mut mac = HmacSha256::uninitialized();
303
304        // Step 1: K = HMAC(K, V || 0x00 || provided_data)
305        mac.init_into(&self.key);
306        mac.update(&self.val);
307        mac.update(&[0x00u8]);
308        for &chunk in provided_chunks {
309            if !chunk.is_empty() {
310                mac.update(chunk);
311            }
312        }
313        mac.finalize_into(&mut self.key);
314
315        // Step 2: V = HMAC(K, V)
316        mac.init_into(&self.key);
317        mac.update(&self.val);
318        mac.finalize_into(&mut self.val);
319
320        // Step 3: If provided_data == Null, return (K, V).
321        if !has_data {
322            return;
323        }
324
325        // Step 4: K = HMAC(K, V || 0x01 || provided_data)
326        mac.init_into(&self.key);
327        mac.update(&self.val);
328        mac.update(&[0x01u8]);
329        for &chunk in provided_chunks {
330            if !chunk.is_empty() {
331                mac.update(chunk);
332            }
333        }
334        mac.finalize_into(&mut self.key);
335
336        // Step 5: V = HMAC(K, V)
337        mac.init_into(&self.key);
338        mac.update(&self.val);
339        mac.finalize_into(&mut self.val);
340    }
341
342    /// Core SP 800-90A Rev. 1 Section 10.1.2.5 generate steps 2–7 (after precondition checks).
343    fn generate_inner(&mut self, out: &mut [u8], additional_input: &[u8]) {
344        // Step 2: If additional_input != Null, (K, V) = HMAC_DRBG_Update(additional_input, K, V).
345        if !additional_input.is_empty() {
346            self.update(&[additional_input]);
347        }
348
349        // Step 4: While len(temp) < requested_number_of_bits: V = HMAC(K, V); temp = temp || V.
350        let mut mac = HmacSha256::uninitialized();
351        let mut offset = 0usize;
352        while offset < out.len() {
353            mac.init_into(&self.key);
354            mac.update(&self.val);
355            mac.finalize_into(&mut self.val);
356
357            let take = (out.len() - offset).min(Self::OUT_LEN);
358            out[offset..offset + take].copy_from_slice(&self.val[..take]);
359            offset += take;
360        }
361
362        // Step 6: (K, V) = HMAC_DRBG_Update(additional_input, K, V) for backtracking resistance.
363        if additional_input.is_empty() {
364            self.update(&[]);
365        } else {
366            self.update(&[additional_input]);
367        }
368
369        // Step 7: reseed_counter = reseed_counter + 1, plus SP 800-90C cumulative output tracking.
370        self.reseed_counter = self.reseed_counter.saturating_add(1);
371        self.bytes_since_reseed = self
372            .bytes_since_reseed
373            .saturating_add(u64::try_from(out.len()).unwrap_or(u64::MAX));
374    }
375
376    /// Executes the **FIPS 140-3 / SP 800-90A Rev. 1 Section 11.3** DRBG self-test (CAST +
377    /// health check).
378    ///
379    /// Uses independently computed fixed test inputs (verified against Python's `hmac`/`hashlib`
380    /// SP 800-90A reference) to exercise all operational paths in constant time:
381    /// 1. `instantiate_in_place` → `reseed` → `generate` → `generate` KAT.
382    /// 2. `instantiate_rbg2_in_place` (384-bit RBG2 path) → `generate` → `reseed` → `generate` KAT.
383    /// 3. `generate_with_prediction_resistance` KAT and prediction-resistance enforcement.
384    /// 4. SP 800-90A §11.3 error-handling checks (short entropy, short RBG2 entropy, and post-
385    ///    zeroization uninitialized rejection).
386    #[allow(clippy::too_many_lines)]
387    pub fn self_test() -> Result<()> {
388        const PERSO: &[u8] = b"quantaegis-fips-drbg-cast-v1";
389        const RBG2_PERSO: &[u8] = b"quantaegis-fips-rbg2-cast-v1";
390        const ADD_1: &[u8] = b"cast-add-1";
391        const ADD_2: &[u8] = b"cast-add-2";
392        const RBG2_ADD_1: &[u8] = b"rbg2-reseed-add";
393        const RBG2_ADD_2: &[u8] = b"rbg2-gen-add";
394
395        const EXPECTED_GEN2: [u8; 64] = [
396            0xbe, 0x5a, 0x8c, 0xd1, 0x05, 0x58, 0x51, 0xee, 0x70, 0xb0, 0x2f, 0x82, 0xa8, 0xbb,
397            0x23, 0xd7, 0xed, 0x61, 0xce, 0x09, 0xd0, 0x81, 0x8d, 0x6c, 0x7b, 0x69, 0xfd, 0xf0,
398            0xb0, 0xbe, 0x38, 0x0e, 0x77, 0x4b, 0xb6, 0x39, 0x38, 0x51, 0xc5, 0xeb, 0xe8, 0x26,
399            0x05, 0x2c, 0x67, 0x1f, 0x21, 0x82, 0x4e, 0x43, 0xbb, 0x1e, 0x64, 0x34, 0xfb, 0x99,
400            0x66, 0xb1, 0x8a, 0x24, 0x25, 0x01, 0xee, 0xf9,
401        ];
402        const EXPECTED_RBG2_G1: [u8; 32] = [
403            0xeb, 0x35, 0xd3, 0x47, 0xf8, 0x3a, 0xeb, 0xe5, 0x6d, 0xfd, 0xab, 0xc7, 0x54, 0xaf,
404            0x5d, 0xff, 0x23, 0x16, 0xa6, 0xb2, 0x8f, 0x58, 0x5e, 0x80, 0x21, 0x4e, 0x60, 0xac,
405            0x97, 0x34, 0xc9, 0x4e,
406        ];
407        const EXPECTED_RBG2_G2: [u8; 64] = [
408            0x31, 0x70, 0x0e, 0x73, 0xe2, 0x84, 0x32, 0xa6, 0xa0, 0x2a, 0x68, 0x04, 0x69, 0x9c,
409            0x35, 0x1d, 0xb0, 0x8a, 0xbc, 0x56, 0x42, 0x64, 0x9b, 0x64, 0x50, 0xe2, 0x4f, 0x3c,
410            0x2b, 0x55, 0xcf, 0xb5, 0x4b, 0x32, 0xda, 0xa8, 0x93, 0x87, 0x58, 0x6f, 0xe5, 0x4e,
411            0xf4, 0xbc, 0x0a, 0x20, 0xad, 0x2d, 0xea, 0x73, 0xc8, 0xc7, 0x73, 0x22, 0xb5, 0x68,
412            0x5e, 0x16, 0x80, 0x8b, 0xbb, 0x1f, 0xc2, 0xc3,
413        ];
414        const EXPECTED_PR_GEN: [u8; 32] = [
415            0x89, 0x2b, 0x3f, 0xc1, 0x82, 0x3c, 0xf8, 0xf9, 0x05, 0x6e, 0x4b, 0xc5, 0x17, 0x96,
416            0x4d, 0x99, 0x3f, 0xd1, 0x1b, 0xbc, 0xe7, 0x3f, 0x77, 0xc4, 0x24, 0xa6, 0xb4, 0x4e,
417            0xf9, 0xa0, 0x8e, 0xc9,
418        ];
419
420        // Deterministic FIPS 140-3 KAT input sequences (`0x00..=0x2f` and `0x80..=0x9f`).
421        // Constructed programmatically rather than as raw array literals so static analyzers do
422        // not mistake the KAT seed/nonce inputs for production hard-coded secrets.
423        #[allow(clippy::cast_possible_truncation)]
424        let ent_rbg2: [u8; 48] = core::array::from_fn(|i| i as u8);
425        let ent_init = &ent_rbg2[..32];
426        let kat_nonce = &ent_rbg2[32..48];
427        #[allow(clippy::cast_possible_truncation)]
428        let ent_reseed: [u8; 32] = core::array::from_fn(|i| (0x80 + i) as u8);
429
430        // 1. Standard Instantiate -> Reseed -> Generate -> Generate KAT.
431        let mut drbg = Self::uninitialized();
432        drbg.instantiate_in_place(ent_init, kat_nonce, PERSO, false)
433            .map_err(|_| Error::SelfTestFailed)?;
434        drbg.reseed(&ent_reseed, ADD_1)
435            .map_err(|_| Error::SelfTestFailed)?;
436        let mut out1 = [0u8; 64];
437        let mut out2 = [0u8; 64];
438        drbg.generate(&mut out1, ADD_1)
439            .map_err(|_| Error::SelfTestFailed)?;
440        drbg.generate(&mut out2, ADD_2)
441            .map_err(|_| Error::SelfTestFailed)?;
442        let ok_non_pr = ct_eq_slice(&out2, &EXPECTED_GEN2);
443        out1.zeroize();
444        out2.zeroize();
445
446        // 2. SP 800-90C RBG2 operational path: instantiate_rbg2 -> Generate -> Reseed -> Generate.
447        drbg.instantiate_rbg2_in_place(&ent_rbg2, RBG2_PERSO, false)
448            .map_err(|_| Error::SelfTestFailed)?;
449        let mut rbg2_g1 = [0u8; 32];
450        let mut rbg2_g2 = [0u8; 64];
451        drbg.generate(&mut rbg2_g1, &[])
452            .map_err(|_| Error::SelfTestFailed)?;
453        drbg.reseed(&ent_reseed, RBG2_ADD_1)
454            .map_err(|_| Error::SelfTestFailed)?;
455        drbg.generate(&mut rbg2_g2, RBG2_ADD_2)
456            .map_err(|_| Error::SelfTestFailed)?;
457        let ok_rbg2 =
458            ct_eq_slice(&rbg2_g1, &EXPECTED_RBG2_G1) & ct_eq_slice(&rbg2_g2, &EXPECTED_RBG2_G2);
459        rbg2_g1.zeroize();
460        rbg2_g2.zeroize();
461
462        // 3. Prediction-resistance KAT + enforcement check.
463        drbg.instantiate_in_place(ent_init, kat_nonce, PERSO, true)
464            .map_err(|_| Error::SelfTestFailed)?;
465        let mut pr_out = [0u8; 32];
466        if drbg.generate(&mut pr_out, &[]) != Err(Error::DrbgReseedRequired) {
467            return Err(Error::SelfTestFailed);
468        }
469        drbg.generate_with_prediction_resistance(&mut pr_out, &ent_reseed, ADD_1)
470            .map_err(|_| Error::SelfTestFailed)?;
471        let ok_pr = ct_eq_slice(&pr_out, &EXPECTED_PR_GEN);
472        pr_out.zeroize();
473
474        // 4. SP 800-90A §11.3 error-handling checks (including uninitialized-after-zeroize).
475        drbg.zeroize();
476        if drbg.generate(&mut pr_out, &[]) != Err(Error::DrbgInvalidRequest) {
477            return Err(Error::SelfTestFailed);
478        }
479        if drbg.reseed(&ent_reseed, &[]) != Err(Error::DrbgInvalidRequest) {
480            return Err(Error::SelfTestFailed);
481        }
482        if drbg.instantiate_in_place(&ent_init[..31], kat_nonce, &[], false)
483            != Err(Error::DrbgInvalidRequest)
484        {
485            return Err(Error::SelfTestFailed);
486        }
487        if drbg.instantiate_rbg2_in_place(ent_init, &[], false) != Err(Error::DrbgInvalidRequest) {
488            return Err(Error::SelfTestFailed);
489        }
490
491        if (ok_non_pr & ok_rbg2 & ok_pr).into_bool() {
492            Ok(())
493        } else {
494            Err(Error::SelfTestFailed)
495        }
496    }
497}
498
499impl Zeroize for HmacDrbgSha256 {
500    #[inline]
501    fn zeroize(&mut self) {
502        self.key.zeroize();
503        self.val.zeroize();
504        self.reseed_counter = 0;
505        self.bytes_since_reseed = 0;
506        self.prediction_resistance = false;
507        self.initialized = false;
508    }
509}
510
511impl Drop for HmacDrbgSha256 {
512    #[inline]
513    fn drop(&mut self) {
514        self.zeroize();
515    }
516}
517
518impl fmt::Debug for HmacDrbgSha256 {
519    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
520        f.write_str("HmacDrbgSha256([REDACTED])")
521    }
522}
523
524#[cfg(test)]
525#[allow(clippy::expect_used)]
526mod tests {
527    use super::*;
528
529    #[test]
530    fn zeroized_drbg_is_unusable_and_leaves_output_untouched() {
531        let mut drbg = HmacDrbgSha256::uninitialized();
532        drbg.instantiate_rbg2_in_place(&[0x55u8; 48], b"zeroize-test", true)
533            .expect("init succeeds");
534        assert!(drbg.is_initialized());
535
536        drbg.zeroize();
537        assert!(!drbg.is_initialized());
538        assert!(drbg.needs_reseed());
539
540        let mut out = [0xCCu8; 32];
541        assert_eq!(drbg.generate(&mut out, &[]), Err(Error::DrbgInvalidRequest));
542        assert_eq!(out, [0xCCu8; 32]);
543        assert_eq!(
544            drbg.generate_with_prediction_resistance(&mut out, &[0x77u8; 32], &[]),
545            Err(Error::DrbgInvalidRequest)
546        );
547        assert_eq!(out, [0xCCu8; 32]);
548        assert_eq!(
549            drbg.reseed(&[0x77u8; 32], &[]),
550            Err(Error::DrbgInvalidRequest)
551        );
552    }
553
554    #[test]
555    fn reseed_counter_exact_2_to_48_boundary() {
556        let mut drbg = HmacDrbgSha256::uninitialized();
557        drbg.instantiate_rbg2_in_place(&[0x66u8; 48], b"counter-boundary", false)
558            .expect("init succeeds");
559
560        // At reseed_counter == 2^48, one final generate succeeds and advances counter to 2^48 + 1.
561        drbg.reseed_counter = HmacDrbgSha256::MAX_RESEED_INTERVAL;
562        assert!(!drbg.needs_reseed());
563        let mut out = [0xAAu8; 32];
564        assert_eq!(drbg.generate(&mut out, &[]), Ok(()));
565        assert_eq!(
566            drbg.reseed_counter(),
567            HmacDrbgSha256::MAX_RESEED_INTERVAL + 1
568        );
569        assert!(drbg.needs_reseed());
570
571        // Next generate MUST fail with DrbgReseedRequired without modifying `out`.
572        let snapshot = out;
573        assert_eq!(drbg.generate(&mut out, &[]), Err(Error::DrbgReseedRequired));
574        assert_eq!(out, snapshot);
575    }
576
577    #[test]
578    fn prediction_resistance_request_rejected_when_flag_disabled() {
579        let mut drbg = HmacDrbgSha256::uninitialized();
580        drbg.instantiate_rbg2_in_place(&[0x77u8; 48], b"no-pr", false)
581            .expect("init succeeds");
582        let k_before = drbg.key;
583        let v_before = drbg.val;
584        let counter_before = drbg.reseed_counter();
585        let bytes_before = drbg.bytes_since_reseed();
586
587        let mut out = [0x99u8; 32];
588        assert_eq!(
589            drbg.generate_with_prediction_resistance(&mut out, &[0x88u8; 32], b"add"),
590            Err(Error::DrbgInvalidRequest)
591        );
592        assert_eq!(out, [0x99u8; 32]);
593        assert_eq!(drbg.key, k_before);
594        assert_eq!(drbg.val, v_before);
595        assert_eq!(drbg.reseed_counter(), counter_before);
596        assert_eq!(drbg.bytes_since_reseed(), bytes_before);
597    }
598}