Skip to main content

kyberlib/
rng.rs

1// Copyright © 2024 kyberlib. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! RNG helpers.
5//!
6//! kyberlib's public surface consumes generic [`rand_core::RngCore`]
7//! + [`rand_core::CryptoRng`] — see the function signatures in
8//! [`crate::api`] and [`crate::ml_kem`]. The single helper exported
9//! here ([`randombytes`](crate::rng::randombytes)) wraps
10//! `RngCore::try_fill_bytes` to surface kyberlib's
11//! [`KyberLibError::RandomBytesGeneration`]
12//! variant on external-RNG faults.
13
14use crate::KyberLibError;
15use rand_core::{CryptoRng, RngCore};
16
17/// Fills a buffer `x` with `len` bytes of random data.
18///
19/// This function uses a random number generator (RNG) that satisfies both
20/// the `RngCore` and `CryptoRng` traits. The RNG is used to generate `len`
21/// random bytes and fill the buffer `x` with these bytes.
22///
23/// # Arguments
24///
25/// * `x` - A mutable slice of bytes to be filled with random data.
26/// * `len` - The number of random bytes to generate.
27/// * `rng` - A mutable reference to the RNG.
28///
29/// # Errors
30///
31/// If the RNG fails to generate the required number of bytes, an error
32/// of type `KyberLibError::RandomBytesGeneration` is returned.
33///
34/// # Examples
35///
36/// ```
37/// use kyberlib::rng::randombytes;
38/// use rand_core::OsRng;
39///
40/// let mut buffer = [0u8; 32];
41/// let len = buffer.len();
42/// randombytes(&mut buffer, len, &mut OsRng).expect("OsRng cannot fail");
43/// ```
44///
45/// # Notes
46///
47/// Ensure that the length of the buffer `x` is at least `len` bytes,
48/// otherwise the function will panic due to out-of-bounds memory access.
49pub fn randombytes<R>(
50    x: &mut [u8],
51    len: usize,
52    rng: &mut R,
53) -> Result<(), KyberLibError>
54where
55    R: RngCore + CryptoRng,
56{
57    if len > x.len() {
58        return Err(KyberLibError::InvalidLength);
59    }
60
61    rng.try_fill_bytes(&mut x[..len])
62        .map_err(|_| KyberLibError::RandomBytesGeneration)
63}