aboutsummaryrefslogtreecommitdiff
path: root/src/rand.rs
diff options
context:
space:
mode:
authorNicholas Rodrigues Lordello <[email protected]>2020-11-30 12:58:44 +0100
committerNicholas Rodrigues Lordello <[email protected]>2020-11-30 12:58:44 +0100
commit678d45e7ae09510796d27a80ecd894f6a1ad8279 (patch)
tree56e9dc6cc093faadd86da1edebc76334c00b6a74 /src/rand.rs
parentbd7a6880f5dce74fd154f593a5a5f7034affeee4 (diff)
generate random mnemonic
Diffstat (limited to 'src/rand.rs')
-rw-r--r--src/rand.rs36
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());
+ }
+}