Skip to main content

quantica/ml_dsa/
rng.rs

1//! Minimal cryptographic RNG trait and OS-backed implementation.
2//!
3//! Provides the [`CryptoRng`] trait used by ML-DSA for key generation and
4//! hedged signing, along with [`OsRng`], a simple implementation backed by
5//! the operating system's entropy source.
6
7use super::MlDsaError;
8
9/// Trait for cryptographic random byte generation.
10///
11/// Implementors must fill the destination buffer with cryptographically
12/// secure random bytes. This trait is used as a trait object (`&mut dyn CryptoRng`)
13/// throughout the ML-DSA API to allow callers to supply their own RNG.
14pub trait CryptoRng {
15    /// Fill `dest` with cryptographically secure random bytes.
16    ///
17    /// # Errors
18    ///
19    /// Returns [`MlDsaError::RngFailure`] if the underlying entropy source
20    /// is unavailable or fails.
21    fn fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), MlDsaError>;
22}
23
24/// OS-backed cryptographic RNG reading from `/dev/urandom`.
25///
26/// Only available with the `std` feature. In `no_std` builds, callers
27/// must supply their own [`CryptoRng`] implementation.
28#[cfg(feature = "std")]
29pub struct OsRng;
30
31#[cfg(feature = "std")]
32impl CryptoRng for OsRng {
33    fn fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), MlDsaError> {
34        use std::io::Read;
35        let mut f = std::fs::File::open("/dev/urandom").map_err(|_| MlDsaError::RngFailure)?;
36        f.read_exact(dest).map_err(|_| MlDsaError::RngFailure)
37    }
38}