|
| 1 | +pub use rand; |
| 2 | + |
| 3 | +use rand::{CryptoRng, RngCore}; |
| 4 | + |
| 5 | +/// The secure interface for cryptographically-secure random numbers |
| 6 | +pub struct HostRng; |
| 7 | + |
| 8 | +impl CryptoRng for HostRng {} |
| 9 | + |
| 10 | +impl RngCore for HostRng { |
| 11 | + #[inline] |
| 12 | + fn next_u32(&mut self) -> u32 { |
| 13 | + crate::random::random::get_random_u64() as _ |
| 14 | + } |
| 15 | + |
| 16 | + #[inline] |
| 17 | + fn next_u64(&mut self) -> u64 { |
| 18 | + crate::random::random::get_random_u64() |
| 19 | + } |
| 20 | + |
| 21 | + fn fill_bytes(&mut self, dest: &mut [u8]) { |
| 22 | + let n = dest.len(); |
| 23 | + if usize::BITS <= u64::BITS || n <= u64::MAX as _ { |
| 24 | + dest.copy_from_slice(&crate::random::random::get_random_bytes(n as _)); |
| 25 | + } else { |
| 26 | + let (head, tail) = dest.split_at_mut(u64::MAX as _); |
| 27 | + head.copy_from_slice(&crate::random::random::get_random_bytes(u64::MAX)); |
| 28 | + self.fill_bytes(tail); |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + #[inline] |
| 33 | + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { |
| 34 | + self.fill_bytes(dest); |
| 35 | + Ok(()) |
| 36 | + } |
| 37 | +} |
| 38 | + |
| 39 | +/// The insecure interface for insecure pseudo-random numbers |
| 40 | +pub struct HostInsecureRng; |
| 41 | + |
| 42 | +impl RngCore for HostInsecureRng { |
| 43 | + #[inline] |
| 44 | + fn next_u32(&mut self) -> u32 { |
| 45 | + crate::random::insecure::get_insecure_random_u64() as _ |
| 46 | + } |
| 47 | + |
| 48 | + #[inline] |
| 49 | + fn next_u64(&mut self) -> u64 { |
| 50 | + crate::random::insecure::get_insecure_random_u64() |
| 51 | + } |
| 52 | + |
| 53 | + fn fill_bytes(&mut self, dest: &mut [u8]) { |
| 54 | + let n = dest.len(); |
| 55 | + if usize::BITS <= u64::BITS || n <= u64::MAX as _ { |
| 56 | + dest.copy_from_slice(&crate::random::insecure::get_insecure_random_bytes(n as _)); |
| 57 | + } else { |
| 58 | + let (head, tail) = dest.split_at_mut(u64::MAX as _); |
| 59 | + head.copy_from_slice(&crate::random::insecure::get_insecure_random_bytes( |
| 60 | + u64::MAX, |
| 61 | + )); |
| 62 | + self.fill_bytes(tail); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + #[inline] |
| 67 | + fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { |
| 68 | + self.fill_bytes(dest); |
| 69 | + Ok(()) |
| 70 | + } |
| 71 | +} |
0 commit comments