Skip to main content

bssl_crypto/
rand.rs

1// Copyright 2023 The BoringSSL Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Getting random bytes.
16
17use crate::{with_output_array, FfiMutSlice};
18
19/// Fills `buf` with random bytes.
20pub fn rand_bytes(buf: &mut [u8]) {
21    // Safety: `RAND_bytes` writes exactly `buf.len()` bytes.
22    let ret = unsafe { bssl_sys::RAND_bytes(buf.as_mut_ffi_ptr(), buf.len()) };
23
24    // BoringSSL's `RAND_bytes` always succeeds returning 1, or crashes the
25    // address space if the PRNG can not provide random data.
26    debug_assert!(ret == 1);
27}
28
29/// Returns an array of random bytes.
30pub fn rand_array<const N: usize>() -> [u8; N] {
31    unsafe {
32        with_output_array(|out, out_len| {
33            // Safety: `RAND_bytes` writes exactly `out_len` bytes, as required.
34            let ret = bssl_sys::RAND_bytes(out, out_len);
35            // BoringSSL RAND_bytes always succeeds returning 1, or crashes the
36            // address space if the PRNG can not provide random data.
37            debug_assert!(ret == 1);
38        })
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45
46    #[test]
47    fn fill() {
48        let mut buf = [0; 32];
49        rand_bytes(&mut buf);
50    }
51
52    #[test]
53    fn fill_empty() {
54        let mut buf = [];
55        rand_bytes(&mut buf);
56    }
57
58    #[test]
59    fn array() {
60        let _rand: [u8; 32] = rand_array();
61    }
62
63    #[test]
64    fn empty_array() {
65        let _rand: [u8; 0] = rand_array();
66    }
67}