Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add rand_priv_bytes #2126

Merged
merged 2 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions openssl-sys/src/handwritten/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
36 changes: 33 additions & 3 deletions openssl/src/rand.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -50,11 +75,16 @@ pub fn keep_random_devices_open(keep: bool) {

#[cfg(test)]
mod tests {
use super::rand_bytes;

#[test]
fn test_rand_bytes() {
let mut buf = [0; 32];
rand_bytes(&mut buf).unwrap();
super::rand_bytes(&mut buf).unwrap();
}

#[test]
#[cfg(ossl111)]
fn test_rand_priv_bytes() {
let mut buf = [0; 32];
super::rand_priv_bytes(&mut buf).unwrap();
}
}