diff options
| author | Nicholas Rodrigues Lordello <[email protected]> | 2020-11-30 12:58:44 +0100 |
|---|---|---|
| committer | Nicholas Rodrigues Lordello <[email protected]> | 2020-11-30 12:58:44 +0100 |
| commit | 678d45e7ae09510796d27a80ecd894f6a1ad8279 (patch) | |
| tree | 56e9dc6cc093faadd86da1edebc76334c00b6a74 /src/rand.rs | |
| parent | bd7a6880f5dce74fd154f593a5a5f7034affeee4 (diff) | |
generate random mnemonic
Diffstat (limited to 'src/rand.rs')
| -rw-r--r-- | src/rand.rs | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/rand.rs b/src/rand.rs new file mode 100644 index 0000000..e1e74b5 --- /dev/null +++ b/src/rand.rs @@ -0,0 +1,36 @@ +//! Cryptographically secure randomness. + +use std::{io, os::raw::c_int}; + +/// 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()) }; + if result >= 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} + +extern "C" { + fn getentropy(buffer: *mut u8, len: usize) -> c_int; +} + +#[cfg(test)] +mod tests { + use super::*; + + #[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()); + } + + #[test] + fn error_reading_more_than_256_bytes() { + let mut buf = [0u8; 257]; + assert!(get_entropy(&mut buf).is_err()); + } +} |
