1use core::fmt;
25
26use quantaegis_core::ct::ct_eq_slice;
27use quantaegis_core::{Error, Result, Zeroize};
28
29use crate::hmac::HmacSha256;
30
31pub 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 pub const SECURITY_STRENGTH_BITS: usize = 256;
49
50 pub const OUT_LEN: usize = HmacSha256::TAG_LEN;
52
53 pub const MIN_ENTROPY_LEN: usize = 32;
55
56 pub const MIN_NONCE_LEN: usize = 16;
58
59 pub const RBG2_INIT_MIN_ENTROPY_LEN: usize = 48;
62
63 pub const MAX_BYTES_PER_REQUEST: usize = 65_536;
66
67 pub const MAX_RESEED_INTERVAL: u64 = 1u64 << 48;
69
70 pub const SP800_90C_RESEED_BYTES: u64 = 16_384;
74
75 pub const MAX_INPUT_LEN: usize = 1 << 30;
78
79 #[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 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 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 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 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 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 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 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 self.reseed(entropy, additional_input)?;
260 self.generate_inner(out, &[]);
261 Ok(())
262 }
263
264 #[inline]
266 pub const fn is_initialized(&self) -> bool {
267 self.initialized
268 }
269
270 #[inline]
272 pub const fn reseed_counter(&self) -> u64 {
273 self.reseed_counter
274 }
275
276 #[inline]
278 pub const fn bytes_since_reseed(&self) -> u64 {
279 self.bytes_since_reseed
280 }
281
282 #[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 #[inline]
293 pub const fn prediction_resistance(&self) -> bool {
294 self.prediction_resistance
295 }
296
297 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 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 mac.init_into(&self.key);
317 mac.update(&self.val);
318 mac.finalize_into(&mut self.val);
319
320 if !has_data {
322 return;
323 }
324
325 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 mac.init_into(&self.key);
338 mac.update(&self.val);
339 mac.finalize_into(&mut self.val);
340 }
341
342 fn generate_inner(&mut self, out: &mut [u8], additional_input: &[u8]) {
344 if !additional_input.is_empty() {
346 self.update(&[additional_input]);
347 }
348
349 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 if additional_input.is_empty() {
364 self.update(&[]);
365 } else {
366 self.update(&[additional_input]);
367 }
368
369 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 #[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 #[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 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 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 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 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 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 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}