rustls/
rand.rs

1//! The single place where we generate random material for our own use.
2
3use crate::crypto::SecureRandom;
4
5use alloc::vec;
6use alloc::vec::Vec;
7
8/// Make a [`Vec<u8>`] of the given size containing random material.
9pub(crate) fn random_vec(
10    secure_random: &dyn SecureRandom,
11    len: usize,
12) -> Result<Vec<u8>, GetRandomFailed> {
13    let mut v = vec![0; len];
14    secure_random.fill(&mut v)?;
15    Ok(v)
16}
17
18/// Return a uniformly random [`u32`].
19pub(crate) fn random_u32(secure_random: &dyn SecureRandom) -> Result<u32, GetRandomFailed> {
20    let mut buf = [0u8; 4];
21    secure_random.fill(&mut buf)?;
22    Ok(u32::from_be_bytes(buf))
23}
24
25/// Random material generation failed.
26#[derive(Debug)]
27pub struct GetRandomFailed;