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