From 28793e5b07f0fe7ed439d060b532df37909b3637 Mon Sep 17 00:00:00 2001 From: Palash Tyagi <23239946+Magnus167@users.noreply.github.com> Date: Mon, 28 Jul 2025 20:19:01 +0100 Subject: [PATCH] Add CryptoRng for cryptographically secure random number generation --- src/random/crypto.rs | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 src/random/crypto.rs diff --git a/src/random/crypto.rs b/src/random/crypto.rs new file mode 100644 index 0000000..1bd6d8f --- /dev/null +++ b/src/random/crypto.rs @@ -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() +}