add bindings to RAND_bytes Change-Id: I9ec56ae8d4ca0a28dccbf2a04c4c675791c053b8 Reviewed-on: https://boringssl-review.googlesource.com/c/boringssl/+/58265 Commit-Queue: Bob Beck <bbe@google.com> Reviewed-by: Bob Beck <bbe@google.com>
diff --git a/rust/bssl-crypto/src/lib.rs b/rust/bssl-crypto/src/lib.rs index 8400337..9024ed4 100644 --- a/rust/bssl-crypto/src/lib.rs +++ b/rust/bssl-crypto/src/lib.rs
@@ -37,6 +37,9 @@ /// BoringSSL implemented hmac operations. pub mod hmac; +/// BoringSSL implemented cryptographically secure pseudo-random number generation. +pub mod rand; + #[cfg(test)] mod test_helpers;
diff --git a/rust/bssl-crypto/src/rand.rs b/rust/bssl-crypto/src/rand.rs new file mode 100644 index 0000000..9fdbe0a --- /dev/null +++ b/rust/bssl-crypto/src/rand.rs
@@ -0,0 +1,41 @@ +/* Copyright (c) 2023, Google Inc. + * + * Permission to use, copy, modify, and/or distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES + * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF + * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY + * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES + * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION + * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN + * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + */ + +use crate::CSliceMut; + +/// Fills buf with random bytes. In the event that sufficient random data can not be obtained, +/// BoringSSL will abort, so the assert will never be hit. +pub fn rand_bytes(buf: &mut [u8]) { + let mut ffi_buf = CSliceMut::from(buf); + let result = unsafe { bssl_sys::RAND_bytes(ffi_buf.as_mut_ptr(), ffi_buf.len()) }; + assert_eq!(result, 1, "BoringSSL RAND_bytes API failed unexpectedly"); +} + +#[cfg(test)] +mod tests { + use super::rand_bytes; + + #[test] + fn test_rand_bytes() { + let mut buf = [0; 32]; + rand_bytes(&mut buf); + } + + #[test] + fn test_rand_bytes_empty() { + let mut buf = []; + rand_bytes(&mut buf); + } +}