Skip to content

Commit ec8f096

Browse files
committed
Add rand_priv_bytes
`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>
1 parent 5b4edd8 commit ec8f096

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

openssl-sys/src/handwritten/rand.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,9 @@ use libc::*;
33
extern "C" {
44
pub fn RAND_bytes(buf: *mut u8, num: c_int) -> c_int;
55

6+
#[cfg(ossl111)]
7+
pub fn RAND_priv_bytes(buf: *mut u8, num: c_int) -> c_int;
8+
69
#[cfg(ossl111)]
710
pub fn RAND_keep_random_devices_open(keep: c_int);
811

openssl/src/rand.rs

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,31 @@ pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> {
3737
}
3838
}
3939

40+
/// Fill buffer with cryptographically strong pseudo-random bytes. It is
41+
/// intended to be used for generating values that should remain private.
42+
///
43+
/// # Examples
44+
///
45+
/// To generate a buffer with cryptographically strong random bytes:
46+
///
47+
/// ```
48+
/// use openssl::rand::rand_priv_bytes;
49+
///
50+
/// let mut buf = [0; 256];
51+
/// rand_priv_bytes(&mut buf).unwrap();
52+
/// ```
53+
///
54+
/// Requires OpenSSL 1.1.1 or newer.
55+
#[corresponds(RAND_priv_bytes)]
56+
#[cfg(ossl111)]
57+
pub fn rand_priv_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> {
58+
unsafe {
59+
ffi::init();
60+
assert!(buf.len() <= c_int::max_value() as usize);
61+
cvt(ffi::RAND_priv_bytes(buf.as_mut_ptr(), buf.len() as LenType)).map(|_| ())
62+
}
63+
}
64+
4065
/// Controls random device file descriptor behavior.
4166
///
4267
/// Requires OpenSSL 1.1.1 or newer.
@@ -50,11 +75,18 @@ pub fn keep_random_devices_open(keep: bool) {
5075

5176
#[cfg(test)]
5277
mod tests {
53-
use super::rand_bytes;
78+
use super::{rand_bytes, rand_priv_bytes};
5479

5580
#[test]
5681
fn test_rand_bytes() {
5782
let mut buf = [0; 32];
5883
rand_bytes(&mut buf).unwrap();
5984
}
85+
86+
#[test]
87+
#[cfg(ossl111)]
88+
fn test_rand_priv_bytes() {
89+
let mut buf = [0; 32];
90+
rand_priv_bytes(&mut buf).unwrap();
91+
}
6092
}

0 commit comments

Comments
 (0)