diff --git a/openssl-sys/src/handwritten/rand.rs b/openssl-sys/src/handwritten/rand.rs index 3bf9da5921..df553bd144 100644 --- a/openssl-sys/src/handwritten/rand.rs +++ b/openssl-sys/src/handwritten/rand.rs @@ -3,6 +3,9 @@ use libc::*; extern "C" { pub fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int; + #[cfg(ossl111)] + pub fn RAND_priv_bytes(buf: *mut u8, num: c_int) -> c_int; + #[cfg(ossl111)] pub fn RAND_keep_random_devices_open(keep: c_int); diff --git a/openssl/src/rand.rs b/openssl/src/rand.rs index 8317951f81..b4c134b25e 100644 --- a/openssl/src/rand.rs +++ b/openssl/src/rand.rs @@ -37,6 +37,31 @@ pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> { } } +/// Fill buffer with cryptographically strong pseudo-random bytes. It is +/// intended to be used for generating values that should remain private. +/// +/// # Examples +/// +/// To generate a buffer with cryptographically strong random bytes: +/// +/// ``` +/// use openssl::rand::rand_priv_bytes; +/// +/// let mut buf = [0; 256]; +/// rand_priv_bytes(&mut buf).unwrap(); +/// ``` +/// +/// Requires OpenSSL 1.1.1 or newer. +#[corresponds(RAND_priv_bytes)] +#[cfg(ossl111)] +pub fn rand_priv_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> { + unsafe { + ffi::init(); + assert!(buf.len() <= c_int::max_value() as usize); + cvt(ffi::RAND_priv_bytes(buf.as_mut_ptr(), buf.len() as LenType)).map(|_| ()) + } +} + /// Controls random device file descriptor behavior. /// /// Requires OpenSSL 1.1.1 or newer. @@ -50,11 +75,18 @@ pub fn keep_random_devices_open(keep: bool) { #[cfg(test)] mod tests { - use super::rand_bytes; + use super::{rand_bytes, rand_priv_bytes}; #[test] fn test_rand_bytes() { let mut buf = [0; 32]; rand_bytes(&mut buf).unwrap(); } + + #[test] + #[cfg(ossl111)] + fn test_rand_priv_bytes() { + let mut buf = [0; 32]; + rand_priv_bytes(&mut buf).unwrap(); + } }