diff options
Diffstat (limited to 'src/rand.rs')
| -rw-r--r-- | src/rand.rs | 38 |
1 files changed, 27 insertions, 11 deletions
diff --git a/src/rand.rs b/src/rand.rs index e1e74b5..ce5f2df 100644 --- a/src/rand.rs +++ b/src/rand.rs @@ -1,11 +1,22 @@ //! Cryptographically secure randomness. -use std::{io, os::raw::c_int}; +use std::io; -/// Populates the provided slice with cryptographically strong entropy. -pub fn get_entropy(mut buf: impl AsMut<[u8]>) -> io::Result<()> { - let buf = buf.as_mut(); - let result = unsafe { getentropy(buf.as_mut_ptr(), buf.len()) }; +/// The maximum amount of entropy that can be read at a time. +pub const MAX_SIZE: usize = 256; + +/// Fills the specified slice with cryptographically strong entropy. +pub fn fill(buf: &mut [u8]) { + for chunk in buf.chunks_mut(MAX_SIZE) { + getentropy(chunk).expect("chunk size less than max"); + } +} + +/// Populates the specified slice with cryptographically strong entropy. +/// +/// Returns an error if the buffer length is greater than [`MAX_SIZE`]. +pub fn getentropy(buf: &mut [u8]) -> io::Result<()> { + let result = unsafe { ffi::getentropy(buf.as_mut_ptr(), buf.len()) }; if result >= 0 { Ok(()) } else { @@ -13,8 +24,12 @@ pub fn get_entropy(mut buf: impl AsMut<[u8]>) -> io::Result<()> { } } -extern "C" { - fn getentropy(buffer: *mut u8, len: usize) -> c_int; +mod ffi { + use std::ffi::c_int; + + extern "C" { + pub fn getentropy(buffer: *mut u8, len: usize) -> c_int; + } } #[cfg(test)] @@ -24,13 +39,14 @@ mod tests { #[test] fn read_os_entropy() { let mut buf = [0u8; 32]; - assert!(get_entropy(&mut buf[..16]).is_ok()); - assert!(get_entropy(&mut buf).is_ok()); + assert!(getentropy(&mut buf[..16]).is_ok()); + assert!(getentropy(&mut buf).is_ok()); } #[test] fn error_reading_more_than_256_bytes() { - let mut buf = [0u8; 257]; - assert!(get_entropy(&mut buf).is_err()); + let mut buf = [0u8; MAX_SIZE + 1]; + assert!(getentropy(&mut buf[..MAX_SIZE]).is_ok()); + assert!(getentropy(&mut buf).is_err()); } } |
