Skip to main content

paysec_crypto_rustcrypto/
random.rs

1use paysec_crypto::RandomBytes;
2use rand_core::{CryptoRng, OsRng, RngCore};
3
4use crate::{RustCryptoError, RustCryptoProvider, RustCryptoProviderWithRng};
5
6impl RandomBytes for RustCryptoProvider {
7    fn fill_random(&mut self, output: &mut [u8]) -> Result<(), Self::Error> {
8        let mut rng = OsRng;
9
10        rng.try_fill_bytes(output)
11            .map_err(|_| RustCryptoError::random_generation_failed())
12    }
13}
14
15impl<R> RandomBytes for RustCryptoProviderWithRng<R>
16where
17    R: RngCore + CryptoRng,
18{
19    fn fill_random(&mut self, output: &mut [u8]) -> Result<(), Self::Error> {
20        self.rng_mut()
21            .try_fill_bytes(output)
22            .map_err(|_| RustCryptoError::random_generation_failed())
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    struct FixedRng {
31        bytes: Vec<u8>,
32        offset: usize,
33    }
34
35    impl FixedRng {
36        fn new(bytes: impl Into<Vec<u8>>) -> Self {
37            Self {
38                bytes: bytes.into(),
39                offset: 0,
40            }
41        }
42    }
43
44    impl RngCore for FixedRng {
45        fn next_u32(&mut self) -> u32 {
46            let mut bytes = [0u8; 4];
47            self.fill_bytes(&mut bytes);
48            u32::from_le_bytes(bytes)
49        }
50
51        fn next_u64(&mut self) -> u64 {
52            let mut bytes = [0u8; 8];
53            self.fill_bytes(&mut bytes);
54            u64::from_le_bytes(bytes)
55        }
56
57        fn fill_bytes(&mut self, dest: &mut [u8]) {
58            let end = self.offset + dest.len();
59
60            assert!(end <= self.bytes.len(), "fixed RNG exhausted");
61
62            dest.copy_from_slice(&self.bytes[self.offset..end]);
63            self.offset = end;
64        }
65
66        fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand_core::Error> {
67            self.fill_bytes(dest);
68            Ok(())
69        }
70    }
71
72    impl CryptoRng for FixedRng {}
73
74    #[test]
75    fn injected_rng_produces_expected_bytes() {
76        let rng = FixedRng::new([
77            0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
78            0xee, 0xff,
79        ]);
80
81        let mut provider = RustCryptoProvider::with_rng(rng);
82
83        let mut output = [0u8; 16];
84        provider.fill_random(&mut output).unwrap();
85
86        assert_eq!(
87            output,
88            [
89                0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
90                0xee, 0xff,
91            ]
92        );
93    }
94}