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 ffi; 14 use libc::c_int; 15 16 use cvt; 17 use 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 openssl::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 rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack>35pub fn rand_bytes(buf: &mut [u8]) -> Result<(), ErrorStack> { 36 unsafe { 37 ffi::init(); 38 assert!(buf.len() <= c_int::max_value() as usize); 39 cvt(ffi::RAND_bytes(buf.as_mut_ptr(), buf.len() as c_int)).map(|_| ()) 40 } 41 } 42 43 /// Controls random device file descriptor behavior. 44 /// 45 /// Requires OpenSSL 1.1.1 or newer. 46 /// 47 /// This corresponds to [`RAND_keep_random_devices_open`]. 48 /// 49 /// [`RAND_keep_random_devices_open`]: https://www.openssl.org/docs/manmaster/man3/RAND_keep_random_devices_open.html 50 #[cfg(ossl111)] keep_random_devices_open(keep: bool)51pub fn keep_random_devices_open(keep: bool) { 52 unsafe { 53 ffi::RAND_keep_random_devices_open(keep as c_int); 54 } 55 } 56 57 #[cfg(test)] 58 mod tests { 59 use super::rand_bytes; 60 61 #[test] test_rand_bytes()62 fn test_rand_bytes() { 63 let mut buf = [0; 32]; 64 rand_bytes(&mut buf).unwrap(); 65 } 66 } 67