nist-rand 0.1.0

A high-assurance, FIPS 140-3 and NIST SP 800-90A/B/C compliant Cryptographically Secure Pseudorandom Number Generator (CSPRNG) with multi-source entropy blending.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! # Hash_DRBG — NIST SP 800-90A, Rev. 1, § 10.1.1
//!
//! This module implements the **Hash Deterministic Random Bit Generator** (`Hash_DRBG`)
//! specified in NIST SP 800-90A using **SHA3-512** as the approved hash function.
//!
//! ## Why SHA3-512?
//!
//! FIPS 140-3 and SP 800-90A list SHA-2 as the canonical hash for `Hash_DRBG`, but
//! SHA3-512 is an **equally approved** FIPS 202 hash function. Using it here gives
//! us two additional security advantages:
//!
//! 1. **Independent design** — SHA-3 (Keccak) and SHA-2 share no structural lineage,
//!    so a cryptanalytic breakthrough against one does **not** transfer to the other.
//! 2. **Full 512-bit security state** — The 512-bit output matches the internal width
//!    of the state vectors `V` and `C`, giving a **256-bit security strength** (half
//!    the output size per SP 800-57 §5.6.1) — sufficient for Top Secret key generation.
//!
//! ## Algorithm Overview (SP 800-90A § 10.1.1)
//!
//! | Phase          | Reference        | Operation |
//! |----------------|------------------|-----------| 
//! | Instantiate    | § 10.1.1.2       | `V = Hash(seed)` ; `C = Hash(0x00 ‖ V)` |
//! | Reseed         | § 10.1.1.3       | `V = Hash(0x01 ‖ V ‖ entropy)` ; `C = Hash(0x00 ‖ V)` |
//! | Generate       | § 10.1.1.4       | Hashgen → update `V = V + H + C + counter` |
//! | Health check   | § 11 / FIPS 140-3 | Reseed counter enforced; panic on overrun |
//!
//! ## Domain-Separation Prefixes
//!
//! The single-byte prefixes used during hashing exactly match the SP 800-90A
//! specification so that this implementation is **test-vector compatible**:
//!
//! - `0x00` — constant derivation (used to compute `C`)
//! - `0x01` — reseed prefix
//! - `0x03` — post-generate state update (H computation)
//!
//! ## Zeroization
//!
//! When the `zeroize` crate feature is enabled (the default), `HashDrbg` derives
//! [`zeroize::ZeroizeOnDrop`].  This guarantees that the keying material (`V` and `C`)
//! is securely erased from memory even if a panic unwinds the stack before an
//! explicit `drop()` call.  When the feature is disabled a manual `Drop` using
//! `core::ptr::write_volatile` is used as a best-effort fallback.

use core::cmp;
use sha3::{Digest, Sha3_512};

#[cfg(feature = "zeroize")]
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

// ────────────────────────────────────────────────────────────────────────────────
// Constants
// ────────────────────────────────────────────────────────────────────────────────

/// SHA3-512 digest / state-vector length in bytes.
const DIGEST_LEN: usize = 64;

/// Maximum number of `generate` calls permitted between reseeds (SP 800-90A
/// Table 2 allows up to 2^48; we use 10 000 as a conservative, high-assurance
/// value suitable for FIPS 140-3 Level 3 and above).
pub const RESEED_INTERVAL: u64 = 10_000;

// ────────────────────────────────────────────────────────────────────────────────
// Data types
// ────────────────────────────────────────────────────────────────────────────────

/// A NIST SP 800-90A compliant `Hash_DRBG` backed by SHA3-512.
///
/// # Internal State
///
/// | Field            | Width    | Purpose |
/// |------------------|----------|---------| 
/// | `v`              | 512 bits | Working state ("V" in the spec) |
/// | `c`              | 512 bits | Constant derived from `V` ("C" in the spec) |
/// | `reseed_counter` | u64      | Counts `generate` calls since last reseed |
///
/// # Thread Safety
///
/// `HashDrbg` is **not** `Sync`.  Each thread should hold its own instance
/// (see the `thread_local!` in `lib.rs`).
///
/// # Zeroization
///
/// Keying material is securely erased on drop via [`ZeroizeOnDrop`] (when the
/// `zeroize` feature is enabled) or a `write_volatile` fallback otherwise.
#[derive(Debug)]
#[cfg_attr(feature = "zeroize", derive(Zeroize, ZeroizeOnDrop))]
pub struct HashDrbg {
    /// Working state V (512 bits).
    v: [u8; DIGEST_LEN],
    /// Derivation constant C (512 bits).
    c: [u8; DIGEST_LEN],
    /// Number of `generate` calls since the last reseed.
    reseed_counter: u64,
}

// ────────────────────────────────────────────────────────────────────────────────
// Core implementation
// ────────────────────────────────────────────────────────────────────────────────

impl HashDrbg {
    /// Instantiates the DRBG from pre-conditioned entropy (SP 800-90A § 10.1.1.2).
    ///
    /// The `entropy_input` **must** already carry at least 256 bits of min-entropy
    /// (the target security strength).  In this crate, the entropy conditioner in
    /// `entropy::get_blended_entropy()` guarantees exactly `DIGEST_LEN` bytes of
    /// SP 800-90C-conditioned material.
    ///
    /// # State Initialisation
    ///
    /// ```text
    /// V = Hash(entropy_input)
    /// C = Hash(0x00 ‖ V)
    /// reseed_counter = 1
    /// ```
    pub fn instantiate(entropy_input: &[u8]) -> Self {
        // V = Hash(seed)
        let v: [u8; DIGEST_LEN] = sha3_512(entropy_input);

        // C = Hash(0x00 ‖ V)
        let c: [u8; DIGEST_LEN] = sha3_512_chain(&[&[0x00], v.as_ref()]);

        Self { v, c, reseed_counter: 1 }
    }

    /// Reseeds the DRBG with fresh entropy (SP 800-90A § 10.1.1.3).
    ///
    /// The internal state is cryptographically re-mixed, then `reseed_counter`
    /// is reset to `1`.  All forward-secrecy is preserved: an attacker who learns
    /// the new `V` gains **no** information about outputs produced before this
    /// reseed.
    ///
    /// # State Update
    ///
    /// ```text
    /// V = Hash(0x01 ‖ V ‖ entropy_input)
    /// C = Hash(0x00 ‖ V)
    /// reseed_counter = 1
    /// ```
    pub fn reseed(&mut self, entropy_input: &[u8]) {
        self.v = sha3_512_chain(&[&[0x01], self.v.as_ref(), entropy_input]);
        self.c = sha3_512_chain(&[&[0x00], self.v.as_ref()]);
        self.reseed_counter = 1;
    }

    /// Fills `out` with pseudo-random bytes (SP 800-90A § 10.1.1.4).
    ///
    /// # Algorithm — Hashgen + State Update
    ///
    /// **Hashgen phase** (produces `out.len()` bytes):
    /// ```text
    /// m  = V
    /// while bytes_needed > 0:
    ///     W  = Hash(m)
    ///     output W (or a prefix of it)
    ///     m  = m + 1  (big-endian increment)
    /// ```
    ///
    /// **State-update phase** (prevents backtracking):
    /// ```text
    /// H  = Hash(0x03 ‖ V)
    /// V  = (V + H + C + reseed_counter) mod 2^512
    /// reseed_counter += 1
    /// ```
    ///
    /// # Return Value
    ///
    /// Returns `true` on success.  Returns `false` — **without modifying `out`** —
    /// if `reseed_counter` exceeds [`RESEED_INTERVAL`], signalling that the caller
    /// must call [`reseed`](Self::reseed) before retrying.
    pub fn generate(&mut self, out: &mut [u8]) -> bool {
        if self.reseed_counter > RESEED_INTERVAL {
            return false;
        }

        // ── Hashgen ────────────────────────────────────────────────────────────
        // `m` is a copy of V used as the running counter — zeroized on scope exit.
        #[cfg(feature = "zeroize")]
        let mut m = Zeroizing::new(self.v);
        #[cfg(not(feature = "zeroize"))]
        let mut m = self.v;

        let mut offset = 0;

        while offset < out.len() {
            #[cfg(feature = "zeroize")]
            let w = Zeroizing::new(sha3_512(m.as_ref()));
            #[cfg(not(feature = "zeroize"))]
            let w = sha3_512(m.as_ref());

            let n = cmp::min(out.len() - offset, DIGEST_LEN);
            out[offset..offset + n].copy_from_slice(&w[..n]);
            offset += n;
            add_one_be(m.as_mut_slice());
        }

        // ── State update ───────────────────────────────────────────────────────
        // H = Hash(0x03 ‖ V)
        #[cfg(feature = "zeroize")]
        let h = Zeroizing::new(sha3_512_chain(&[&[0x03], self.v.as_ref()]));
        #[cfg(not(feature = "zeroize"))]
        let h = sha3_512_chain(&[&[0x03], self.v.as_ref()]);

        // V = (V + H + C + reseed_counter) mod 2^512
        add_be(&mut self.v, h.as_slice());
        add_be(&mut self.v, &self.c);

        // padded_counter is non-sensitive but zeroized for hygiene.
        #[cfg(feature = "zeroize")]
        let mut padded_counter = Zeroizing::new([0u8; DIGEST_LEN]);
        #[cfg(not(feature = "zeroize"))]
        let mut padded_counter = [0u8; DIGEST_LEN];

        padded_counter[DIGEST_LEN - 8..].copy_from_slice(&self.reseed_counter.to_be_bytes());
        add_be(&mut self.v, padded_counter.as_slice());

        self.reseed_counter += 1;
        true
    }
}

// ────────────────────────────────────────────────────────────────────────────────
// Fallback Drop (when `zeroize` feature is disabled)
// ────────────────────────────────────────────────────────────────────────────────

/// When the `zeroize` crate is not available, use `write_volatile` to prevent
/// the compiler from eliding the zeroing as dead-store elimination.
#[cfg(not(feature = "zeroize"))]
impl Drop for HashDrbg {
    fn drop(&mut self) {
        for b in self.v.iter_mut().chain(self.c.iter_mut()) {
            // SAFETY: pointer is valid and aligned; volatile prevents dead-store elision.
            unsafe { core::ptr::write_volatile(b, 0) };
        }
        // SAFETY: same rationale; also prevents counter leakage.
        unsafe { core::ptr::write_volatile(&mut self.reseed_counter, 0) };
    }
}

// ────────────────────────────────────────────────────────────────────────────────
// Private helpers
// ────────────────────────────────────────────────────────────────────────────────

/// Computes SHA3-512 of a single contiguous slice.
#[inline]
fn sha3_512(data: &[u8]) -> [u8; DIGEST_LEN] {
    let mut h = Sha3_512::new();
    h.update(data);
    let digest = h.finalize();
    let mut out = [0u8; DIGEST_LEN];
    out.copy_from_slice(&digest);
    out
}

/// Computes SHA3-512 over a sequence of slices (avoids intermediate allocation).
#[inline]
fn sha3_512_chain(parts: &[&[u8]]) -> [u8; DIGEST_LEN] {
    let mut h = Sha3_512::new();
    for part in parts {
        h.update(part);
    }
    let digest = h.finalize();
    let mut out = [0u8; DIGEST_LEN];
    out.copy_from_slice(&digest);
    out
}

/// Adds `1` to a big-endian byte array in place, wrapping on overflow.
///
/// This is the big-endian counter increment required for the Hashgen loop in
/// SP 800-90A § 10.1.1.4 ("m = m + 1").
fn add_one_be(arr: &mut [u8]) {
    for byte in arr.iter_mut().rev() {
        let (new_val, overflow) = byte.overflowing_add(1);
        *byte = new_val;
        if !overflow {
            break;
        }
    }
}

/// Adds `src` to `dest` treating both as big-endian integers, wrapping on
/// overflow (mod 2^(8 × `dest.len()`)).
///
/// Used for the SP 800-90A § 10.1.1.4 state update:
/// `V = (V + H + C + reseed_counter) mod 2^512`.
///
/// # Panics
///
/// Does **not** panic if `src` is shorter than `dest`; excess high bytes of
/// `dest` are left unchanged.  Behaviour is unspecified if `src` is longer
/// than `dest` (the extra bytes are silently ignored due to the `zip` iterator).
fn add_be(dest: &mut [u8], src: &[u8]) {
    let mut carry = 0u16;
    for (d, s) in dest.iter_mut().rev().zip(src.iter().rev()) {
        let sum = *d as u16 + *s as u16 + carry;
        *d = sum as u8;
        carry = sum >> 8;
    }
    // Intentionally drops carry on overflow (mod 2^512 arithmetic).
}

// ────────────────────────────────────────────────────────────────────────────────
// Tests
// ────────────────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    // ── Functional tests ─────────────────────────────────────────────────────

    #[test]
    fn instantiate_and_generate_differ() {
        let entropy = [0x42u8; DIGEST_LEN];
        let mut drbg = HashDrbg::instantiate(&entropy);

        let mut out1 = [0u8; 32];
        assert!(drbg.generate(&mut out1), "first generate must succeed");

        let mut out2 = [0u8; 32];
        assert!(drbg.generate(&mut out2), "second generate must succeed");

        assert_ne!(out1, out2, "successive outputs must differ");
        assert!(out1.iter().any(|&b| b != 0), "output must not be all-zero");
    }

    #[test]
    fn different_seeds_produce_different_output() {
        let mut drbg1 = HashDrbg::instantiate(&[0x11u8; DIGEST_LEN]);
        let mut drbg2 = HashDrbg::instantiate(&[0x22u8; DIGEST_LEN]);

        let mut out1 = [0u8; DIGEST_LEN];
        let mut out2 = [0u8; DIGEST_LEN];
        drbg1.generate(&mut out1);
        drbg2.generate(&mut out2);
        assert_ne!(out1, out2);
    }

    #[test]
    fn reseed_resets_counter_and_changes_output() {
        let entropy1 = [0x11u8; DIGEST_LEN];
        let entropy2 = [0x22u8; DIGEST_LEN];

        let mut drbg = HashDrbg::instantiate(&entropy1);
        let mut before = [0u8; DIGEST_LEN];
        drbg.generate(&mut before);

        drbg.reseed(&entropy2);
        assert_eq!(drbg.reseed_counter, 1, "counter must reset after reseed");

        let mut after = [0u8; DIGEST_LEN];
        assert!(drbg.generate(&mut after));
        assert_ne!(before, after, "output must change after reseed");
    }

    #[test]
    fn multi_block_generate_produces_distinct_blocks() {
        let mut drbg = HashDrbg::instantiate(&[0x55u8; DIGEST_LEN]);
        let mut out = [0u8; DIGEST_LEN * 8]; // 8 × 64-byte blocks
        assert!(drbg.generate(&mut out));

        assert!(out.iter().any(|&b| b != 0));
        assert_ne!(
            &out[..DIGEST_LEN],
            &out[DIGEST_LEN..DIGEST_LEN * 2],
            "consecutive blocks must differ"
        );
    }

    // ── Reseed-interval enforcement ───────────────────────────────────────────

    #[test]
    fn generate_succeeds_at_reseed_interval() {
        let mut drbg = HashDrbg::instantiate(&[0xAAu8; DIGEST_LEN]);
        drbg.reseed_counter = RESEED_INTERVAL;

        let mut out = [0u8; 32];
        assert!(drbg.generate(&mut out), "must succeed when counter == RESEED_INTERVAL");
        assert_eq!(drbg.reseed_counter, RESEED_INTERVAL + 1);
    }

    #[test]
    fn generate_fails_after_reseed_interval() {
        let mut drbg = HashDrbg::instantiate(&[0xAAu8; DIGEST_LEN]);
        drbg.reseed_counter = RESEED_INTERVAL + 1;

        let mut out = [0u8; 32];
        assert!(!drbg.generate(&mut out), "must fail when counter > RESEED_INTERVAL");
    }

    // ── Big-endian arithmetic helpers ─────────────────────────────────────────

    #[test]
    fn add_one_be_basic() {
        let mut arr = [0u8; 4];
        add_one_be(&mut arr);
        assert_eq!(arr, [0, 0, 0, 1]);
    }

    #[test]
    fn add_one_be_carry_propagation() {
        let mut arr = [0, 0, 0, 0xFF];
        add_one_be(&mut arr);
        assert_eq!(arr, [0, 0, 1, 0]);
    }

    #[test]
    fn add_one_be_wraparound() {
        let mut arr = [0xFF; 4];
        add_one_be(&mut arr);
        assert_eq!(arr, [0; 4], "must wrap around (mod 2^32)");
    }

    #[test]
    fn add_be_no_carry() {
        let mut dest = [0, 0, 0, 5];
        add_be(&mut dest, &[0, 0, 0, 10]);
        assert_eq!(dest, [0, 0, 0, 15]);
    }

    #[test]
    fn add_be_with_carry() {
        let mut dest = [0, 0, 0, 250];
        add_be(&mut dest, &[0, 0, 0, 10]);
        assert_eq!(dest, [0, 0, 1, 4]); // 260 = 256 + 4
    }

    #[test]
    fn add_be_wraparound() {
        let mut dest = [0xFF; 4];
        add_be(&mut dest, &[0, 0, 0, 1]);
        assert_eq!(dest, [0; 4], "must wrap around (mod 2^32)");
    }

    // ── Zeroization test ─────────────────────────────────────────────────────

    /// Verify that calling `zeroize()` on a live `HashDrbg` clears both `v` and `c`.
    /// This is a sound alternative to inspecting freed memory after `drop()`.
    #[test]
    #[cfg(feature = "zeroize")]
    fn drbg_state_is_zeroed_on_explicit_zeroize() {
        use zeroize::Zeroize;
        let mut drbg = HashDrbg::instantiate(&[0xBBu8; DIGEST_LEN]);
        let mut buf = [0u8; 32];
        drbg.generate(&mut buf);

        // V and C should be non-zero after generation.
        assert!(drbg.v.iter().any(|&b| b != 0), "v must be non-zero before zeroize");
        assert!(drbg.c.iter().any(|&b| b != 0), "c must be non-zero before zeroize");

        // After explicit zeroize both fields must be all-zero.
        drbg.zeroize();
        assert!(drbg.v.iter().all(|&b| b == 0), "v must be zeroed after explicit zeroize");
        assert!(drbg.c.iter().all(|&b| b == 0), "c must be zeroed after explicit zeroize");
        assert_eq!(drbg.reseed_counter, 0, "counter must be zeroed after explicit zeroize");
    }
}