Skip to main content

bitwarden_crypto_primitives/
random.rs

1//! Cryptographically secure random number generation from the backend's CSPRNG.
2
3use std::convert::Infallible;
4
5use rand::{TryCryptoRng, TryRng};
6
7use crate::backend;
8
9/// The backend CSPRNG as a [`rand`] generator.
10///
11/// Prefer `bitwarden_random::rng()` in SDK code: it adds the test seeding hook on top of this.
12#[derive(Clone, Copy, Debug, Default)]
13pub struct SystemRng;
14
15impl TryRng for SystemRng {
16    type Error = Infallible;
17
18    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
19        let mut buf = [0u8; 4];
20        fill_bytes(&mut buf);
21        Ok(u32::from_le_bytes(buf))
22    }
23
24    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
25        let mut buf = [0u8; 8];
26        fill_bytes(&mut buf);
27        Ok(u64::from_le_bytes(buf))
28    }
29
30    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
31        fill_bytes(dst);
32        Ok(())
33    }
34}
35
36impl TryCryptoRng for SystemRng {}
37
38/// Fills `dst` with random bytes from the backend CSPRNG.
39pub fn fill_bytes(dst: &mut [u8]) {
40    backend::random::fill_bytes(dst);
41}
42
43#[cfg(test)]
44mod tests {
45    use super::*;
46
47    #[test]
48    fn fills_distinct_bytes() {
49        let mut a = [0u8; 32];
50        let mut b = [0u8; 32];
51        fill_bytes(&mut a);
52        fill_bytes(&mut b);
53        assert_ne!(a, b);
54    }
55}