Skip to main content

boring/
rand.rs

1//! Utilities for secure random number generation.
2//!
3//! # Examples
4//!
5//! To generate a buffer with cryptographically strong bytes:
6//!
7//! ```
8//! use boring::rand::rand_bytes;
9//!
10//! let mut buf = [0; 256];
11//! rand_bytes(&mut buf).unwrap();
12//! ```
13use crate::ffi;
14use libc::c_int;
15
16use crate::cvt;
17use crate::error::ErrorStack;
18
19/// Fill buffer with cryptographically strong pseudo-random bytes.
20///
21/// This corresponds to [`RAND_bytes`].
22///
23/// # Examples
24///
25/// To generate a buffer with cryptographically strong bytes:
26///
27/// ```
28/// use boring::rand::rand_bytes;
29///
30/// let mut buf = [0; 256];
31/// rand_bytes(&mut buf).unwrap();
32/// ```
33///
34/// [`RAND_bytes`]: https://www.openssl.org/docs/man1.1.0/crypto/RAND_bytes.html
35pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> {
36    unsafe {
37        ffi::init();
38        assert!(buf.len() <= c_int::MAX as usize);
39        cvt(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len()))
40    }
41}
42
43#[cfg(test)]
44mod tests {
45    use super::rand_bytes;
46
47    #[test]
48    fn test_rand_bytes() {
49        let mut buf = [0; 32];
50        rand_bytes(&mut buf).unwrap();
51    }
52}