Add CryptoRng for cryptographically secure random number generation

This commit is contained in:
Palash Tyagi 2025-07-28 20:19:01 +01:00
parent d75bd7a08f
commit 28793e5b07

32
src/random/crypto.rs Normal file
View File

@ -0,0 +1,32 @@
use std::fs::File;
use std::io::Read;
use crate::random::Rng;
/// Cryptographically secure RNG sourcing randomness from `/dev/urandom`.
pub struct CryptoRng {
file: File,
}
impl CryptoRng {
/// Open `/dev/urandom` and create a new generator.
pub fn new() -> Self {
let file = File::open("/dev/urandom").expect("failed to open /dev/urandom");
Self { file }
}
}
impl Rng for CryptoRng {
fn next_u64(&mut self) -> u64 {
let mut buf = [0u8; 8];
self.file
.read_exact(&mut buf)
.expect("failed reading from /dev/urandom");
u64::from_ne_bytes(buf)
}
}
/// Convenience constructor for [`CryptoRng`].
pub fn crypto_rng() -> CryptoRng {
CryptoRng::new()
}