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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
#![allow(
    clippy::uninlined_format_args,
    clippy::must_use_candidate,
    clippy::cast_precision_loss,
    clippy::cast_lossless,
    clippy::manual_clamp,
    clippy::unused_self,
    clippy::unnecessary_wraps,
    clippy::struct_excessive_bools,
    clippy::doc_markdown,
    clippy::too_many_lines,
    clippy::similar_names
)]
// Unit tests and test-only modules use unwrap/expect/println! for brevity; production `--lib` checks
// still enforce these lints because `cfg(test)` is off for that build.
#![cfg_attr(
    test,
    allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::print_stdout,
        clippy::print_stderr
    )
)]

//! # lib-q-random: Secure Random Number Generation for libQ
//!
//! This crate provides a comprehensive, secure random number generation system
//! designed specifically for post-quantum cryptography applications in the libQ ecosystem.
//!
//! ## Features
//!
//! - **Cryptographically Secure**: Uses OS entropy sources; on x86 / `x86_64`
//!   with `std`, optional **RDRAND** is available through the hardware entropy source
//! - **Multiple Providers**: Support for OS, deterministic, and hardware entropy sources
//! - **Entropy Validation**: Comprehensive entropy quality assessment and validation
//! - **`no_std` Support**: Works in constrained environments without standard library
//! - **WASM Compatible**: Full support for `WebAssembly` and browser environments
//! - **Zero-Copy**: Efficient memory usage with minimal allocations
//! - **Thread-Safe**: Safe for use in multi-threaded environments
//! - **Extensible**: Plugin architecture for custom entropy sources
//! - **Custom Entropy Sources**: Secure callback-based system for plugging in custom entropy sources in `no_std` and WASM environments
//!
//! ## Quick Start
//!
//! ### With std/alloc features
//! ```rust
//! #[cfg(feature = "alloc")]
//! {
//!     use lib_q_random::{
//!         EntropySource,
//!         LibQRng,
//!         RngProvider,
//!     };
//!     use rand_core::Rng;
//!
//!     // Create a secure RNG for production use
//!     let mut rng = LibQRng::new_secure().unwrap();
//!
//!     // Generate random bytes
//!     let mut bytes = [0u8; 32];
//!     rng.fill_bytes(&mut bytes);
//!
//!     // Create a deterministic RNG for testing (32-byte KT128 seed)
//!     let mut test_rng = LibQRng::new_deterministic([1; 32]);
//! }
//! ```
//!
//! ### Custom Entropy Sources (`no_std`/WASM)
//! ```rust
//! #[cfg(feature = "custom-entropy")]
//! {
//!     use lib_q_random::{
//!         custom_entropy::{CustomEntropySource, EntropyContext, EntropyQuality, CustomEntropyConfig},
//!         register_custom_entropy_source, unregister_custom_entropy_source,
//!         new_secure_rng
//!     };
//!     use rand_core::Rng;
//!
//!     // Define your custom entropy callback
//!     unsafe extern "C" fn my_entropy_callback(dest: *mut u8, len: usize, _context: *mut u8) -> i32 {
//!         // Fill dest with len bytes of entropy from your source
//!         for i in 0..len {
//!             unsafe {
//!                 *dest.add(i) = (i as u8).wrapping_add(42); // Example entropy source
//!             }
//!         }
//!         0
//!     }
//!
//!     // Create and register the custom entropy source
//!     let context = EntropyContext::empty();
//!     let config = CustomEntropyConfig::default();
//!     let source = CustomEntropySource {
//!         callback: my_entropy_callback,
//!         context,
//!         quality: EntropyQuality::Hardware,
//!         config,
//!         source_id: "my_hardware_rng",
//!     };
//!
//!     // Register the source (must remain valid for the lifetime of usage)
//!     unsafe {
//!         register_custom_entropy_source(&source);
//!     }
//!
//!     // Now create RNGs that will use your custom entropy source
//!     let mut rng = new_secure_rng().unwrap();
//!     let mut bytes = [0u8; 32];
//!     rng.fill_bytes(&mut bytes);
//!
//!     // Clean up when done
//!     unregister_custom_entropy_source();
//! }
//! ```
//!
//! ### With `no_std` features
//! ```rust,no_run
//! #[cfg(not(feature = "alloc"))]
//! {
//!     use lib_q_random::{
//!         new_deterministic_rng_no_std,
//!         new_secure_rng_no_std,
//!     };
//!     use rand_core::Rng;
//!
//!     // Create a secure RNG for production use
//!     let mut rng = new_secure_rng_no_std().unwrap();
//!
//!     // Generate random bytes
//!     let mut bytes = [0u8; 32];
//!     rng.fill_bytes(&mut bytes);
//!
//!     // Create a deterministic RNG for testing
//!     let mut test_rng = new_deterministic_rng_no_std([1; 32]);
//! }
//! ```
//!
//! ## Architecture
//!
//! The crate is organized into several key components:
//!
//! - **Core Traits**: Define the interface for RNG providers and entropy sources
//! - **Providers**: Implement different RNG strategies (OS, deterministic, hardware)
//! - **Validation**: Entropy quality assessment and security validation
//! - **Factory**: RNG creation and configuration management
//!
//! ## Security Considerations
//!
//! - **Production randomness** comes from OS or registered hardware/custom entropy sources;
//!   APIs return an error when secure entropy is unavailable instead of substituting weak RNGs.
//! - **Deterministic constructors** (`LibQRng::new_deterministic`, `NoStdRng::new_deterministic`,
//!   `new_deterministic_rng`, etc.) use **KT128** (`KangarooTwelve`) XOF expansion keyed by the caller’s
//!   32-byte seed (or SplitMix64-expanded `u64` for `*_from_u64`).
//!   They are for tests, KATs, and reproducible benchmarks: treat the seed like a symmetric key;
//!   if it is guessable, the entire stream is guessable.
//! - Entropy validation applies to non-deterministic sources.
//! - Secure memory clearing and constant-time expectations are documented per algorithm crate.

#![cfg_attr(not(feature = "std"), no_std)]
#![warn(missing_docs, clippy::all, clippy::pedantic)]
#![allow(clippy::module_name_repetitions)]

// Heap-backed APIs (`Vec`, `Box`, …) require explicit `alloc` (see Cargo features). With `cdylib`,
// standalone `cargo check` of this crate uses the `no_std` feature, which enables `no_std_panic_handler`.
#[cfg(feature = "alloc")]
extern crate alloc;

#[cfg(all(not(feature = "std"), feature = "no_std_panic_handler"))]
mod no_std_panic_handler {
    use core::panic::PanicInfo;

    #[panic_handler]
    #[allow(clippy::empty_loop)]
    fn panic(_info: &PanicInfo) -> ! {
        loop {}
    }
}

mod hardware_rng;
pub mod kt128_expander;

#[cfg(feature = "deterministic-saturnin")]
pub mod saturnin_det;

// Core modules
pub mod entropy;
pub mod error;
pub mod provider;
pub mod traits;
pub mod validation;

#[cfg(feature = "wasm")]
mod wasm;

// Specialized RNG implementations for different algorithms
pub mod specialized;

// no_std RNG implementation
#[cfg(any(not(feature = "std"), feature = "no_std"))]
pub mod no_std_rng;

// Deterministic RNG for STARK/ZKP use
pub mod deterministic_rng;
pub use deterministic_rng::DeterministicRng;
pub use kt128_expander::{
    DOMAIN_HPKE_RNG,
    DOMAIN_LIBQ_DET_RNG,
    KT128_DET_GOLDEN_U64_SEED_64,
    KT128_DET_GOLDEN_ZERO_SEED_64,
    Kt128Expander,
};

// Custom entropy source system for no_std/WASM environments
#[cfg(feature = "custom-entropy")]
pub mod custom_entropy;

// Re-export main types
pub use error::{
    Error,
    Result,
};
#[cfg(feature = "alloc")]
pub use provider::LibQRng;
// Re-export specialized implementations
#[cfg(feature = "classical-mceliece")]
pub use specialized::ClassicalMcElieceRng;
#[cfg(feature = "fn-dsa")]
pub use specialized::FnDsaRng;
#[cfg(all(feature = "hpke", feature = "hash"))]
pub use specialized::Kt128Rng;
#[cfg(feature = "alloc")]
pub use traits::RngProvider;
pub use traits::{
    EntropySource,
    SecureRng,
    SecurityLevel,
};
// Re-export validation types
pub use validation::{
    EntropyQuality,
    EntropyValidator,
};

/// Version information
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Minimum entropy bits required for cryptographic operations
pub const MIN_ENTROPY_BITS: usize = 128;

/// Maximum entropy bits for validation
pub const MAX_ENTROPY_BITS: usize = 4096;

/// Default entropy buffer size
pub const DEFAULT_ENTROPY_SIZE: usize = 32;

/// Fill `dest` with cryptographically secure bytes from the OS entropy source.
///
/// Requires the `getrandom` feature. Returns `Err` if that feature is absent
/// rather than silently producing weak output.
///
/// # Errors
///
/// Returns [`Error::FeatureNotAvailable`] when the `getrandom` feature is not
/// enabled. Returns [`Error::EntropySourceUnavailable`] when getrandom fails.
pub fn fill_entropy(dest: &mut [u8]) -> Result<()> {
    #[cfg(feature = "getrandom")]
    {
        getrandom::fill(dest).map_err(|_| Error::EntropySourceUnavailable {
            source: "system",
            context: Some("getrandom failed"),
        })
    }
    #[cfg(not(feature = "getrandom"))]
    {
        let _ = dest;
        Err(Error::FeatureNotAvailable {
            feature: "secure entropy",
            required_features: &["getrandom"],
        })
    }
}

/// Create a new secure RNG instance
///
/// This function creates a cryptographically secure RNG using the best available
/// entropy source for the current platform.
///
/// # Errors
///
/// Returns an error if no secure entropy source is available.
///
/// # Examples
///
/// ```rust
/// use lib_q_random::new_secure_rng;
/// use rand_core::Rng;
///
/// let mut rng = new_secure_rng().unwrap();
/// let mut bytes = [0u8; 32];
/// rng.fill_bytes(&mut bytes);
/// ```
#[cfg(feature = "alloc")]
pub fn new_secure_rng() -> Result<LibQRng> {
    LibQRng::new_secure()
}

/// Create a new secure RNG instance for `no_std` environments
///
/// This function creates a cryptographically secure RNG that works in `no_std`
/// environments using getrandom for entropy.
///
/// # Errors
///
/// Returns an error if getrandom is not available or fails to initialize.
///
/// # Examples
///
/// ```rust,no_run
/// use lib_q_random::new_secure_rng_no_std;
/// use rand_core::Rng;
///
/// let mut rng = new_secure_rng_no_std().unwrap();
/// let mut bytes = [0u8; 32];
/// rng.fill_bytes(&mut bytes);
/// ```
#[cfg(not(feature = "alloc"))]
pub fn new_secure_rng_no_std() -> Result<no_std_rng::NoStdRng> {
    no_std_rng::NoStdRng::new()
}

/// Create a new deterministic RNG instance
///
/// This function creates a deterministic RNG suitable for testing and
/// reproducible operations. Output is a **KT128** XOF stream from `seed`.
/// **Unpredictability is only as strong as the seed**; use [`new_secure_rng`]
/// for production cryptography.
///
/// # Arguments
///
/// * `seed` - 32-byte seed for KT128 expansion
///
/// # Examples
///
/// ```rust
/// use lib_q_random::new_deterministic_rng;
/// use rand_core::Rng;
///
/// let mut rng = new_deterministic_rng([1; 32]);
/// let mut bytes = [0u8; 32];
/// rng.fill_bytes(&mut bytes);
/// ```
#[cfg(feature = "alloc")]
#[must_use]
pub fn new_deterministic_rng(seed: [u8; 32]) -> LibQRng {
    LibQRng::new_deterministic(seed)
}

/// Create a deterministic RNG from a `u64` test seed (`SplitMix64` → KT128).
#[cfg(feature = "alloc")]
#[must_use]
pub fn new_deterministic_rng_from_u64(seed: u64) -> LibQRng {
    LibQRng::new_deterministic_from_u64(seed)
}

/// Create a new deterministic RNG instance for `no_std` environments
///
/// This function creates a deterministic RNG suitable for testing and
/// reproducible operations in `no_std` environments. KT128 stream from `seed`;
/// **not** unpredictable unless the seed is secret and high-entropy.
///
/// # Arguments
///
/// * `seed` - 32-byte seed
///
/// # Examples
///
/// ```rust,no_run
/// use lib_q_random::new_deterministic_rng_no_std;
/// use rand_core::Rng;
///
/// let mut rng = new_deterministic_rng_no_std([1; 32]);
/// let mut bytes = [0u8; 32];
/// rng.fill_bytes(&mut bytes);
/// ```
#[cfg(not(feature = "alloc"))]
#[must_use]
pub fn new_deterministic_rng_no_std(seed: [u8; 32]) -> no_std_rng::NoStdRng {
    no_std_rng::NoStdRng::new_deterministic(seed)
}

/// Create a deterministic `no_std` RNG from a `u64` test seed (`SplitMix64` → KT128).
#[cfg(not(feature = "alloc"))]
#[must_use]
pub fn new_deterministic_rng_no_std_from_u64(seed: u64) -> no_std_rng::NoStdRng {
    no_std_rng::NoStdRng::new_deterministic_from_u64(seed)
}

/// Register a custom entropy source for the current thread
///
/// This function allows developers to register a custom entropy source that will
/// be used by `NoStdRng` when generating random bytes. The entropy source must
/// remain valid for the lifetime of the registration.
///
/// # Arguments
///
/// * `source` - The custom entropy source to register
///
/// # Safety
///
/// The `source` must remain valid for the lifetime of the registration.
/// The caller is responsible for ensuring the source is not dropped
/// while registered.
///
/// # Examples
///
/// ```rust,no_run
/// use lib_q_random::custom_entropy::{
///     CustomEntropyConfig,
///     CustomEntropySource,
///     EntropyContext,
///     EntropyQuality,
/// };
/// use lib_q_random::{
///     register_custom_entropy_source,
///     unregister_custom_entropy_source,
/// };
/// use rand_core::Rng;
///
/// // Define a custom entropy callback
/// unsafe extern "C" fn my_entropy_callback(
///     dest: *mut u8,
///     len: usize,
///     _context: *mut u8,
/// ) -> i32 {
///     // Fill dest with len bytes of entropy
///     // Return 0 on success, non-zero on failure
///     0
/// }
///
/// // Create and register the entropy source
/// let context = EntropyContext::empty();
/// let config = CustomEntropyConfig::default();
/// let source = unsafe {
///     CustomEntropySource::new(
///         my_entropy_callback,
///         context,
///         EntropyQuality::User,
///         config,
///         "my_custom_source",
///     )
/// };
///
/// unsafe {
///     register_custom_entropy_source(&source);
/// }
///
/// // Now NoStdRng will use the custom entropy source
/// // (In no_std environments, use new_secure_rng_no_std())
/// // let mut rng = new_secure_rng_no_std().unwrap();
/// // let mut bytes = [0u8; 32];
/// // rng.fill_bytes(&mut bytes);
///
/// // Clean up
/// unregister_custom_entropy_source();
/// ```
#[cfg(feature = "custom-entropy")]
pub unsafe fn register_custom_entropy_source(source: *const custom_entropy::CustomEntropySource) {
    unsafe { custom_entropy::register_custom_entropy_source(source) };
}

/// Unregister the current custom entropy source
///
/// This function removes the currently registered custom entropy source,
/// causing `NoStdRng` to fall back to the default entropy source (getrandom).
#[cfg(feature = "custom-entropy")]
pub fn unregister_custom_entropy_source() {
    custom_entropy::unregister_custom_entropy_source();
}

/// Check if a custom entropy source is currently registered
///
/// # Returns
///
/// Returns `true` if a custom entropy source is registered, `false` otherwise.
#[cfg(feature = "custom-entropy")]
#[must_use]
pub fn has_custom_entropy_source() -> bool {
    custom_entropy::has_custom_entropy_source()
}

/// Get information about the currently registered entropy source
///
/// # Returns
///
/// Returns a tuple of (`source_id`, quality) if a source is registered.
#[cfg(feature = "custom-entropy")]
#[must_use]
pub fn get_custom_entropy_source_info() -> Option<(&'static str, custom_entropy::EntropyQuality)> {
    custom_entropy::get_entropy_source_info()
}

/// Create a new RNG with custom entropy source
///
/// This function allows creating an RNG with a custom entropy source,
/// useful for specialized applications or testing.
///
/// # Arguments
///
/// * `entropy_source` - Custom entropy source implementation
///
/// # Examples
///
/// ```rust
/// use lib_q_random::{
///     EntropySource,
///     new_custom_rng,
/// };
/// use rand_core::Rng;
///
/// struct MyEntropySource;
/// impl EntropySource for MyEntropySource {
///     fn get_entropy(
///         &mut self,
///         dest: &mut [u8],
///     ) -> Result<(), lib_q_random::Error> {
///         // Implementation details...
///         Ok(())
///     }
/// }
///
/// let mut rng = new_custom_rng(MyEntropySource);
/// ```
#[cfg(feature = "alloc")]
pub fn new_custom_rng<T: EntropySource + 'static>(entropy_source: T) -> LibQRng {
    LibQRng::new_custom(entropy_source)
}

#[cfg(test)]
mod tests {
    #[cfg(not(feature = "alloc"))]
    use rand_core::Rng;

    use super::*;

    #[test]
    fn test_version_constant() {
        // VERSION is a non-empty string constant
        #[allow(clippy::const_is_empty)]
        {
            assert!(!VERSION.is_empty());
        }
    }

    #[test]
    fn test_constants() {
        // Test that constants have reasonable values
        #[allow(clippy::assertions_on_constants)]
        {
            assert!(MIN_ENTROPY_BITS >= 128);
            assert!(MAX_ENTROPY_BITS > MIN_ENTROPY_BITS);
            assert!(DEFAULT_ENTROPY_SIZE > 0);
        }
    }

    #[test]
    #[cfg(not(feature = "alloc"))]
    fn test_deterministic_rng_creation() {
        let mut seed = [0u8; 32];
        seed[..8].copy_from_slice(&[1, 2, 3, 4, 5, 6, 7, 8]);
        let rng = new_deterministic_rng_no_std(seed);
        assert!(rng.is_deterministic());
    }

    #[test]
    #[cfg(not(feature = "alloc"))]
    fn test_deterministic_rng_consistency() {
        let seed = [42u8; 32];
        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);

        assert_eq!(bytes1, bytes2);
    }
}