lib-q-random 0.0.4

Unified secure random number generation for libQ post-quantum cryptography library
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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
//! Security tests for lib-q-random
//!
//! These tests ensure that the RNG implementation meets cryptographic security requirements.

#![allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::panic,
    clippy::print_stdout,
    clippy::print_stderr
)]
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(not(feature = "std"))]
extern crate alloc;

// Conditional imports based on feature flags
#[cfg(feature = "alloc")]
use lib_q_random::{
    new_deterministic_rng,
    new_secure_rng,
};
#[cfg(not(feature = "alloc"))]
use lib_q_random::{
    new_deterministic_rng_no_std,
    new_secure_rng_no_std,
};
use rand_core::Rng;

fn pad_label(s: &[u8]) -> [u8; 32] {
    assert!(s.len() <= 32);
    let mut out = [0u8; 32];
    out[..s.len()].copy_from_slice(s);
    out
}

/// Test that secure RNG never produces all zeros
#[test]
fn test_secure_rng_never_produces_zeros() {
    #[cfg(feature = "alloc")]
    {
        let mut rng = new_secure_rng().expect("Failed to create secure RNG");

        // Test multiple calls to ensure we never get all zeros
        for _ in 0..100 {
            let mut bytes = [0u8; 32];
            rng.fill_bytes(&mut bytes);

            // Ensure we never get all zeros
            assert_ne!(bytes, [0u8; 32], "Secure RNG produced all zeros!");

            // Ensure we have some non-zero bytes
            let non_zero_count = bytes.iter().filter(|&&b| b != 0).count();
            assert!(non_zero_count > 0, "Secure RNG produced no non-zero bytes!");
        }
    }

    #[cfg(not(feature = "alloc"))]
    {
        let mut rng = new_secure_rng_no_std().expect("Failed to create secure RNG");

        // Test multiple calls to ensure we never get all zeros
        for _ in 0..100 {
            let mut bytes = [0u8; 32];
            rng.fill_bytes(&mut bytes);

            // Ensure we never get all zeros
            assert_ne!(bytes, [0u8; 32], "Secure RNG produced all zeros!");

            // Ensure we have some non-zero bytes
            let non_zero_count = bytes.iter().filter(|&&b| b != 0).count();
            assert!(non_zero_count > 0, "Secure RNG produced no non-zero bytes!");
        }
    }
}

/// Test that secure RNG produces different values on successive calls
#[test]
fn test_secure_rng_produces_different_values() {
    #[cfg(feature = "alloc")]
    {
        let mut rng = new_secure_rng().expect("Failed to create secure RNG");

        let mut prev_bytes = [0u8; 32];
        rng.fill_bytes(&mut prev_bytes);

        // Test that successive calls produce different values
        for _ in 0..50 {
            let mut bytes = [0u8; 32];
            rng.fill_bytes(&mut bytes);

            // Very high probability that they should be different
            assert_ne!(
                bytes, prev_bytes,
                "Secure RNG produced identical values on successive calls!"
            );
            prev_bytes = bytes;
        }
    }

    #[cfg(not(feature = "alloc"))]
    {
        let mut rng = new_secure_rng_no_std().expect("Failed to create secure RNG");

        let mut prev_bytes = [0u8; 32];
        rng.fill_bytes(&mut prev_bytes);

        // Test that successive calls produce different values
        for _ in 0..50 {
            let mut bytes = [0u8; 32];
            rng.fill_bytes(&mut bytes);

            // Very high probability that they should be different
            assert_ne!(
                bytes, prev_bytes,
                "Secure RNG produced identical values on successive calls!"
            );
            prev_bytes = bytes;
        }
    }
}

/// Test that different RNG instances produce different values
#[test]
fn test_different_rng_instances_produce_different_values() {
    #[cfg(feature = "alloc")]
    {
        let mut rng1 = new_secure_rng().expect("Failed to create secure RNG 1");
        let mut rng2 = new_secure_rng().expect("Failed to create secure RNG 2");

        let mut bytes1 = [0u8; 32];
        let mut bytes2 = [0u8; 32];

        rng1.fill_bytes(&mut bytes1);
        rng2.fill_bytes(&mut bytes2);

        // Different instances should produce different values
        assert_ne!(
            bytes1, bytes2,
            "Different RNG instances produced identical values!"
        );
    }

    #[cfg(not(feature = "alloc"))]
    {
        let mut rng1 = new_secure_rng_no_std().expect("Failed to create secure RNG 1");
        let mut rng2 = new_secure_rng_no_std().expect("Failed to create secure RNG 2");

        let mut bytes1 = [0u8; 32];
        let mut bytes2 = [0u8; 32];

        rng1.fill_bytes(&mut bytes1);
        rng2.fill_bytes(&mut bytes2);

        // Different instances should produce different values
        assert_ne!(
            bytes1, bytes2,
            "Different RNG instances produced identical values!"
        );
    }
}

/// Test that deterministic RNG produces consistent values
#[test]
fn test_deterministic_rng_consistency() {
    let seed = pad_label(b"test seed for deterministic RNG");

    #[cfg(feature = "alloc")]
    {
        let mut rng1 = new_deterministic_rng(seed);
        let mut rng2 = new_deterministic_rng(seed);

        let mut bytes1 = [0u8; 32];
        let mut bytes2 = [0u8; 32];

        rng1.fill_bytes(&mut bytes1);
        rng2.fill_bytes(&mut bytes2);

        // Deterministic RNGs with same seed should produce same values
        assert_eq!(
            bytes1, bytes2,
            "Deterministic RNGs with same seed produced different values!"
        );
    }

    #[cfg(not(feature = "alloc"))]
    {
        let mut rng1 = new_deterministic_rng_no_std(seed);
        let mut rng2 = new_deterministic_rng_no_std(seed);

        let mut bytes1 = [0u8; 32];
        let mut bytes2 = [0u8; 32];

        rng1.fill_bytes(&mut bytes1);
        rng2.fill_bytes(&mut bytes2);

        // Deterministic RNGs with same seed should produce same values
        assert_eq!(
            bytes1, bytes2,
            "Deterministic RNGs with same seed produced different values!"
        );
    }
}

/// Test that deterministic RNGs with different seeds produce different values
#[test]
fn test_deterministic_rng_different_seeds() {
    let seed1 = pad_label(b"seed 1");
    let seed2 = pad_label(b"seed 2");

    #[cfg(feature = "alloc")]
    {
        let mut rng1 = new_deterministic_rng(seed1);
        let mut rng2 = new_deterministic_rng(seed2);

        let mut bytes1 = [0u8; 32];
        let mut bytes2 = [0u8; 32];

        rng1.fill_bytes(&mut bytes1);
        rng2.fill_bytes(&mut bytes2);

        // Different seeds should produce different values
        assert_ne!(
            bytes1, bytes2,
            "Deterministic RNGs with different seeds produced identical values!"
        );
    }

    #[cfg(not(feature = "alloc"))]
    {
        let mut rng1 = new_deterministic_rng_no_std(seed1);
        let mut rng2 = new_deterministic_rng_no_std(seed2);

        let mut bytes1 = [0u8; 32];
        let mut bytes2 = [0u8; 32];

        rng1.fill_bytes(&mut bytes1);
        rng2.fill_bytes(&mut bytes2);

        // Different seeds should produce different values
        assert_ne!(
            bytes1, bytes2,
            "Deterministic RNGs with different seeds produced identical values!"
        );
    }
}

/// Test entropy quality of secure RNG
#[test]
#[cfg(feature = "alloc")]
fn test_secure_rng_entropy_quality() {
    let mut rng = new_secure_rng().expect("Failed to create secure RNG");

    // Collect a large sample of random data
    let mut samples = Vec::new();
    for _ in 0..1000 {
        let mut bytes = [0u8; 16];
        rng.fill_bytes(&mut bytes);
        samples.extend_from_slice(&bytes);
    }

    // Test basic entropy properties
    test_byte_distribution(&samples);
    test_autocorrelation(&samples);
    test_runs_test(&samples);
}

/// Pearson χ² uniformity test over byte histogram (256 bins).
///
/// Requiring every bin to stay within a fixed fraction of the mean is unsound: with 256 bins,
/// the largest multinomial count routinely exceeds ~4–5σ even when bytes are i.i.d. uniform,
/// which made this suite flaky in CI. χ² aggregates deviation across bins with the correct null.
#[cfg(feature = "alloc")]
fn test_byte_distribution(data: &[u8]) {
    let n = data.len();
    assert!(
        n >= 256 * 10,
        "need enough samples for byte histogram (got {})",
        n
    );

    let mut byte_counts = [0u32; 256];
    for &byte in data {
        byte_counts[byte as usize] += 1;
    }

    let expected = n as f64 / 256.0;
    let mut chi_sq = 0.0;
    for &count in &byte_counts {
        let o = f64::from(count);
        let diff = o - expected;
        chi_sq += diff * diff / expected;
    }

    // Asymptotically χ²(255) under uniform i.i.d.; bound upper tail ~1e-5 via normal approx.
    // mean = 255, sd = sqrt(2 * 255).
    const DF: f64 = 255.0;
    let sd = (2.0 * DF).sqrt();
    // z ≈ 4.42 ⇒ one-sided p ≈ 5e-6; keeps CI stable while still catching strong bias.
    const Z: f64 = 4.42;
    let chi_sq_upper = DF + Z * sd;

    assert!(
        chi_sq <= chi_sq_upper,
        "χ² uniformity statistic {:.2} exceeds {:.1} (possible non-uniform bytes; n={})",
        chi_sq,
        chi_sq_upper,
        n
    );
}

/// Lag-1 sample Pearson correlation between adjacent bytes.
///
/// The previous check averaged `(x - 127.5)(y - 127.5)`, which is a *covariance-like*
/// quantity with scale ~Var(U(0,255))²/√n (std dev ~40+ for n≈16k), not a correlation in
/// [-1, 1]. A fixed threshold (e.g. 100) was only ~2–3σ, so bona fide OS RNG output could
/// fail CI sporadically. We instead normalize to Pearson r and bound |r| using ~8/√n_pairs
/// to allow for mild variance inflation from overlapping pairs under an i.i.d. null.
#[cfg(feature = "alloc")]
fn test_autocorrelation(data: &[u8]) {
    let n_pairs = data.len().saturating_sub(1);
    if n_pairs < 2 {
        return;
    }

    let n = n_pairs as f64;
    let mut sum_x = 0.0;
    let mut sum_y = 0.0;
    let mut sum_xx = 0.0;
    let mut sum_yy = 0.0;
    let mut sum_xy = 0.0;

    for i in 0..n_pairs {
        let x = data[i] as f64;
        let y = data[i + 1] as f64;
        sum_x += x;
        sum_y += y;
        sum_xx += x * x;
        sum_yy += y * y;
        sum_xy += x * y;
    }

    let mean_x = sum_x / n;
    let mean_y = sum_y / n;
    let cov = sum_xy / n - mean_x * mean_y;
    let var_x = sum_xx / n - mean_x * mean_x;
    let var_y = sum_yy / n - mean_y * mean_y;

    if var_x <= 1e-12 || var_y <= 1e-12 {
        return;
    }

    let r = cov / (var_x.sqrt() * var_y.sqrt());
    let threshold = 8.0 / n.sqrt();

    assert!(
        r.abs() < threshold,
        "Lag-1 correlation |r|={} exceeds bound {:.4} (~8/√n, n={} pairs)",
        r,
        threshold,
        n_pairs
    );
}

/// Test runs (consecutive identical values)
#[cfg(feature = "alloc")]
fn test_runs_test(data: &[u8]) {
    if data.is_empty() {
        return;
    }

    let mut runs = 1;
    let mut current_byte = data[0];

    for &byte in data.iter().skip(1) {
        if byte != current_byte {
            runs += 1;
            current_byte = byte;
        }
    }

    let expected_runs = data.len() / 2; // Rough expectation  
    let tolerance = ((expected_runs as f64 * 0.5) as usize).max(50); // 50% tolerance, minimum 50

    assert!(
        runs >= expected_runs - tolerance,
        "Too few runs: {} (expected ~{})",
        runs,
        expected_runs
    );
}

/// Test that RNG fails securely when entropy source is unavailable
#[test]
fn test_secure_failure_when_entropy_unavailable() {
    #[cfg(feature = "alloc")]
    {
        // This test would require mocking the entropy source to fail
        // For now, we just ensure the RNG doesn't panic
        let result = new_secure_rng();
        assert!(
            result.is_ok(),
            "RNG creation should not panic even if entropy is limited"
        );
    }

    #[cfg(not(feature = "alloc"))]
    {
        // This test would require mocking the entropy source to fail
        // For now, we just ensure the RNG doesn't panic
        let result = new_secure_rng_no_std();
        assert!(
            result.is_ok(),
            "RNG creation should not panic even if entropy is limited"
        );
    }
}

/// Test that RNG properly handles edge cases
#[test]
fn test_rng_edge_cases() {
    #[cfg(feature = "alloc")]
    {
        let mut rng = new_secure_rng().expect("Failed to create secure RNG");

        // Test filling empty slice
        let mut empty = [];
        rng.fill_bytes(&mut empty);

        // Test filling single byte (0 is a valid output with probability 1/256)
        let mut single = [0u8; 1];
        rng.fill_bytes(&mut single);

        // Test filling large buffer
        let mut large = vec![0u8; 1024];
        rng.fill_bytes(&mut large);

        // Ensure large buffer has some non-zero bytes
        let non_zero_count = large.iter().filter(|&&b| b != 0).count();
        assert!(
            non_zero_count > 0,
            "Large buffer should have non-zero bytes"
        );
    }

    #[cfg(not(feature = "alloc"))]
    {
        let mut rng = new_secure_rng_no_std().expect("Failed to create secure RNG");

        // Test filling empty slice
        let mut empty = [];
        rng.fill_bytes(&mut empty);

        // Test filling single byte (0 is a valid output with probability 1/256)
        let mut single = [0u8; 1];
        rng.fill_bytes(&mut single);

        // Test filling large buffer (using array instead of vec)
        let mut large = [0u8; 1024];
        rng.fill_bytes(&mut large);

        // Ensure large buffer has some non-zero bytes
        let non_zero_count = large.iter().filter(|&&b| b != 0).count();
        assert!(
            non_zero_count > 0,
            "Large buffer should have non-zero bytes"
        );
    }
}

/// Test that RNG maintains security properties across reseeding
#[test]
fn test_rng_security_across_reseeding() {
    #[cfg(feature = "alloc")]
    {
        let mut rng = new_secure_rng().expect("Failed to create secure RNG");

        // Generate data before potential reseeding
        let mut before_bytes = [0u8; 32];
        rng.fill_bytes(&mut before_bytes);

        // Force a reseed by generating a lot of data
        for _ in 0..100 {
            let mut temp = [0u8; 1024];
            rng.fill_bytes(&mut temp);
        }

        // Generate data after reseeding
        let mut after_bytes = [0u8; 32];
        rng.fill_bytes(&mut after_bytes);

        // Both should be non-zero and different
        assert_ne!(
            before_bytes, [0u8; 32],
            "Data before reseed should not be all zeros"
        );
        assert_ne!(
            after_bytes, [0u8; 32],
            "Data after reseed should not be all zeros"
        );
        assert_ne!(
            before_bytes, after_bytes,
            "Data before and after reseed should be different"
        );
    }

    #[cfg(not(feature = "alloc"))]
    {
        let mut rng = new_secure_rng_no_std().expect("Failed to create secure RNG");

        // Generate data before potential reseeding
        let mut before_bytes = [0u8; 32];
        rng.fill_bytes(&mut before_bytes);

        // Force a reseed by generating a lot of data
        for _ in 0..100 {
            let mut temp = [0u8; 1024];
            rng.fill_bytes(&mut temp);
        }

        // Generate data after reseeding
        let mut after_bytes = [0u8; 32];
        rng.fill_bytes(&mut after_bytes);

        // Both should be non-zero and different
        assert_ne!(
            before_bytes, [0u8; 32],
            "Data before reseed should not be all zeros"
        );
        assert_ne!(
            after_bytes, [0u8; 32],
            "Data after reseed should not be all zeros"
        );
        assert_ne!(
            before_bytes, after_bytes,
            "Data before and after reseed should be different"
        );
    }
}