Skip to content

Commit

Permalink
Add rand_priv_bytes
Browse files Browse the repository at this point in the history
`rand_priv_bytes` has the same semantics as `rand_bytes`, and it is
intended to be used for generating values that should remain private.

Signed-off-by: Neil Shen <overvenus@gmail.com>
  • Loading branch information
overvenus committed Dec 13, 2023
1 parent 5b4edd8 commit ec8f096
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
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
34 changes: 33 additions & 1 deletion 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,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();
}
}

0 comments on commit ec8f096

Please sign in to comment.