1 //! Utilities for secure random number generation. 2 //! 3 //! # Examples 4 //! 5 //! To generate a buffer with cryptographically strong bytes: 6 //! 7 //! ``` 8 //! use openssl::rand::rand_bytes; 9 //! 10 //! let mut buf = [0; 256]; 11 //! rand_bytes(&mut buf).unwrap(); 12 //! ``` 13 use libc::c_int; 14 15 use crate::cvt; 16 use crate::error::ErrorStack; 17 18 /// Fill buffer with cryptographically strong pseudo-random bytes. 19 /// 20 /// This corresponds to [`RAND_bytes`]. 21 /// 22 /// # Examples 23 /// 24 /// To generate a buffer with cryptographically strong bytes: 25 /// 26 /// ``` 27 /// use openssl::rand::rand_bytes; 28 /// 29 /// let mut buf = [0; 256]; 30 /// rand_bytes(&mut buf).unwrap(); 31 /// ``` 32 /// 33 /// [`RAND_bytes`]: https://www.openssl.org/docs/man1.1.0/crypto/RAND_bytes.html rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack>34pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> { 35 unsafe { 36 ffi::init(); 37 assert!(buf.len() <= c_int::max_value() as usize); 38 cvt(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int)).map(|_| ()) 39 } 40 } 41 42 /// Controls random device file descriptor behavior. 43 /// 44 /// Requires OpenSSL 1.1.1 or newer. 45 /// 46 /// This corresponds to [`RAND_keep_random_devices_open`]. 47 /// 48 /// [`RAND_keep_random_devices_open`]: https://www.openssl.org/docs/manmaster/man3/RAND_keep_random_devices_open.html 49 #[cfg(ossl111)] keep_random_devices_open(keep: bool)50pub fn keep_random_devices_open(keep: bool) { 51 unsafe { 52 ffi::RAND_keep_random_devices_open(keep as c_int); 53 } 54 } 55 56 #[cfg(test)] 57 mod tests { 58 use super::rand_bytes; 59 60 #[test] test_rand_bytes()61 fn test_rand_bytes() { 62 let mut buf = [0; 32]; 63 rand_bytes(&mut buf).unwrap(); 64 } 65 } 66