Skip to main content

quantica/slh_dsa/
rng.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Cédric Mesnil <cslashm@pm.me>
3
4//! Minimal cryptographic RNG trait and OS-backed implementation.
5//!
6//! SLH-DSA requires a source of cryptographic randomness for key generation and
7//! hedged signing. This module provides a simple trait and a default implementation
8//! backed by the operating system's entropy source.
9
10use super::SlhDsaError;
11
12/// Trait for cryptographic random byte generation.
13///
14/// Implementors must provide bytes that are indistinguishable from uniform random
15/// to any computationally bounded adversary. The default implementation ([`OsRng`])
16/// reads from `/dev/urandom`.
17///
18/// Custom implementations can be provided for testing (deterministic RNG) or for
19/// environments where `/dev/urandom` is unavailable.
20pub trait CryptoRng {
21    /// Fill `dest` with cryptographically secure random bytes.
22    ///
23    /// Returns `Err(SlhDsaError::RngFailure)` if the entropy source is unavailable.
24    fn fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), SlhDsaError>;
25}
26
27/// OS-backed cryptographic RNG reading from `/dev/urandom`.
28///
29/// Only available with the `std` feature. In `no_std` builds, callers
30/// must supply their own [`CryptoRng`] implementation.
31#[cfg(feature = "std")]
32pub struct OsRng;
33
34#[cfg(feature = "std")]
35impl CryptoRng for OsRng {
36    fn fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), SlhDsaError> {
37        use std::io::Read;
38        let mut f = std::fs::File::open("/dev/urandom").map_err(|_| SlhDsaError::RngFailure)?;
39        f.read_exact(dest).map_err(|_| SlhDsaError::RngFailure)
40    }
41}