mirror of
https://github.com/Magnus167/rustframe.git
synced 2025-08-20 04:00:01 +00:00
Add CryptoRng for cryptographically secure random number generation
This commit is contained in:
parent
d75bd7a08f
commit
28793e5b07
32
src/random/crypto.rs
Normal file
32
src/random/crypto.rs
Normal 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()
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user