1 // Copyright 2018 Developers of the Rand project.
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8 
9 //! Entropy generator, or wrapper around external generators
10 
11 #![allow(deprecated)] // whole module is deprecated
12 
13 use crate::rngs::OsRng;
14 use rand_core::{CryptoRng, Error, RngCore};
15 
16 /// An interface returning random data from external source(s), provided
17 /// specifically for securely seeding algorithmic generators (PRNGs).
18 ///
19 /// This is deprecated. It is suggested you use [`rngs::OsRng`] instead.
20 ///
21 /// [`rngs::OsRng`]: crate::rngs::OsRng
22 #[derive(Debug)]
23 #[deprecated(since = "0.7.0", note = "use rngs::OsRng instead")]
24 pub struct EntropyRng {
25     source: OsRng,
26 }
27 
28 impl EntropyRng {
29     /// Create a new `EntropyRng`.
30     ///
31     /// This method will do no system calls or other initialization routines,
32     /// those are done on first use. This is done to make `new` infallible,
33     /// and `try_fill_bytes` the only place to report errors.
new() -> Self34     pub fn new() -> Self {
35         EntropyRng { source: OsRng }
36     }
37 }
38 
39 impl Default for EntropyRng {
default() -> Self40     fn default() -> Self {
41         EntropyRng::new()
42     }
43 }
44 
45 impl RngCore for EntropyRng {
next_u32(&mut self) -> u3246     fn next_u32(&mut self) -> u32 {
47         self.source.next_u32()
48     }
49 
next_u64(&mut self) -> u6450     fn next_u64(&mut self) -> u64 {
51         self.source.next_u64()
52     }
53 
fill_bytes(&mut self, dest: &mut [u8])54     fn fill_bytes(&mut self, dest: &mut [u8]) {
55         self.source.fill_bytes(dest)
56     }
57 
try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error>58     fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Error> {
59         self.source.try_fill_bytes(dest)
60     }
61 }
62 
63 impl CryptoRng for EntropyRng {}
64 
65 
66 #[cfg(test)]
67 mod test {
68     use super::*;
69 
70     #[test]
test_entropy()71     fn test_entropy() {
72         let mut rng = EntropyRng::new();
73         let n = (rng.next_u32() ^ rng.next_u32()).count_ones();
74         assert!(n >= 2); // p(failure) approx 1e-7
75     }
76 }
77