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.
89//! The standard RNG
1011use chacha20::ChaCha12Rng;
12use core::convert::Infallible;
13use rand_core::{SeedableRng, TryCryptoRng, TryRng};
1415/// A strong, fast (amortized), non-portable RNG
16///
17/// This is the "standard" strong PRNG:
18///
19/// - `StdRng` is, like most seedable PRNGs, deterministic: if the generator is
20/// duplicated (for example, by reconstruction with the same seed, by a fork
21/// or by a checkpoint-and-restore of the process), then each clone will yield
22/// identical output (but see also the next point).
23/// - `StdRng` is non-[portable]: any future library version may replace the
24/// algorithm and results may be platform-dependent. (For a portable version,
25/// use a generator named after its algorithm, for example [`ChaCha12Rng`]).
26/// - `StdRng` is a [CSPRNG]: statistically good quality of randomness and
27/// (assuming a good, secret key and secret internal state) [unpredictable]
28/// - `StdRng` is fast
29/// ([amortized](https://en.wikipedia.org/wiki/Amortized_analysis)):
30/// usage of a buffer results in low average cost of each yielded word.
31///
32/// The current algorithm used is the ChaCha block cipher with 12 rounds, i.e.
33/// [`ChaCha12Rng`]. Please see this relevant [rand issue] for the discussion.
34/// This may change as new
35/// evidence of cipher security and performance becomes available.
36///
37/// ## Seeding (construction)
38///
39/// This generator implements the [`SeedableRng`] trait. Any method may be used,
40/// but note that `seed_from_u64` is not suitable for usage where security is
41/// important. Also note that, even with a fixed seed, output is not [portable].
42///
43/// Using a fresh seed **direct from the OS** is the most secure option:
44/// ```
45/// # use rand::{SeedableRng, rngs::{StdRng, SysRng}};
46/// let rng = StdRng::try_from_rng(&mut SysRng).unwrap();
47/// # let _: StdRng = rng;
48/// ```
49///
50/// Seeding via [`rand::make_rng()`] or [`rand::rng()`] may be
51/// faster:
52/// ```
53/// # use rand::rngs::StdRng;
54/// let mut rng: StdRng = rand::make_rng();
55/// # let _ = rand::Rng::next_u32(&mut rng);
56/// ```
57///
58/// Any [`SeedableRng`] method may be used, but note that `seed_from_u64` is not
59/// suitable where security is required. See also [Seeding RNGs] in the book.
60///
61/// ## Generation
62///
63/// The generator implements [`Rng`] and thus also [`RngExt`].
64/// See also the [Random Values] chapter in the book.
65///
66/// [portable]: https://rust-random.github.io/book/crate-reprod.html
67/// [Seeding RNGs]: https://rust-random.github.io/book/guide-seeding.html
68/// [unpredictable]: https://rust-random.github.io/book/guide-rngs.html#security
69/// [Random Values]: https://rust-random.github.io/book/guide-values.html
70/// [CSPRNG]: https://rust-random.github.io/book/guide-gen.html#cryptographically-secure-pseudo-random-number-generator
71/// [chacha20]: https://crates.io/crates/chacha20
72/// [rand issue]: https://github.com/rust-random/rand/issues/932
73/// [`Rng`]: rand_core::Rng
74/// [`RngExt`]: crate::RngExt
75/// [`rand::make_rng()`]: crate::make_rng
76/// [`rand::rng()`]: crate::rng
77#[derive(#[automatically_derived]impl ::core::fmt::Debug for StdRng {
#[inline]
#[rustc_trivial_field_reads]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field1_finish(f, "StdRng",
&&self.0)
}
}Debug, #[automatically_derived]impl ::core::marker::StructuralPartialEq for StdRng {
}
#[automatically_derived]impl ::core::cmp::PartialEq for StdRng {
#[inline]
fn eq(&self, other: &Self) -> bool { self.0 == other.0 }
}PartialEq, #[automatically_derived]impl ::core::cmp::Eq for StdRng {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<ChaCha12Rng>;
}
}Eq)]
78pub struct StdRng(ChaCha12Rng);
7980impl TryRngfor StdRng {
81type Error = Infallible;
8283#[inline(always)]
84fn try_next_u32(&mut self) -> Result<u32, Infallible> {
85self.0.try_next_u32()
86 }
8788#[inline(always)]
89fn try_next_u64(&mut self) -> Result<u64, Infallible> {
90self.0.try_next_u64()
91 }
9293#[inline(always)]
94fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
95self.0.try_fill_bytes(dst)
96 }
97}
9899impl SeedableRngfor StdRng {
100// Fix to 256 bits. Changing this is a breaking change!
101type Seed = [u8; 32];
102103#[inline(always)]
104fn from_seed(seed: Self::Seed) -> Self {
105StdRng(ChaCha12Rng::from_seed(seed))
106 }
107}
108109impl TryCryptoRngfor StdRng {}
110111#[cfg(test)]
112mod test {
113use crate::rngs::StdRng;
114use crate::{Rng, RngExt, SeedableRng};
115116#[test]
117fn test_stdrng_construction() {
118// Test value-stability of StdRng. This is expected to break any time
119 // the algorithm is changed.
120#[rustfmt::skip]
121let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0,
1220,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
123124let target = [10719222850664546238, 14064965282130556830];
125126let mut rng0 = StdRng::from_seed(seed);
127128let x0 = rng0.next_u64();
129130let mut rng1 = StdRng::from_rng(&mut rng0);
131let x1 = rng1.next_u64();
132133assert_eq!([x0, x1], target);
134 }
135136#[test]
137fn test_chacha_true_values_1() {
138// Source: Strombergson 2013, Test Vectors for the Stream Cipher ChaCha
139 // draft-strombergson-chacha-test-vectors-01
140 // https://datatracker.ietf.org/doc/html/draft-strombergson-chacha-test-vectors-01
141 // Converted to LE u128 form (four u128 to one block).
142 // TC: all zero key and IV, rounds 12, 256-bit key
143144let seed = [0u8; 32];
145let mut rng = StdRng::from_seed(seed);
146147let mut results = [0u128; 8];
148 rng.fill(&mut results);
149let expected = [
1500xd583265f12ce1f8153f955076a9af49b,
1510x5f15ae2ea589007e1474e049bbc32904,
1520x798cfaac3428e82cc0e37ad279f86405,
1530xbe2613412fe80b611969dea02c9f623a,
1540x3d17e08c3371fc86fe743e204188d50b,
1550xb489c04c21851515cccbbd19b7eb28c6,
1560x43c88c1b97b802c611f14ca1cd8d2542,
1570x1693e617b0a64427c0515190ca461ee9,
158 ];
159assert_eq!(results, expected);
160161assert_eq!(rng.0.get_word_pos(), 32);
162 }
163164#[test]
165fn test_chacha_true_values_2() {
166// Source: Strombergson 2013, Test Vectors for the Stream Cipher ChaCha
167 // TC2: single bit set in key, all zero IV, rounds 12, 256-bit key
168169let mut seed = [0u8; 32];
170 seed[0] = 1;
171let mut rng = StdRng::from_seed(seed);
172173let mut results = [0u128; 8];
174 rng.fill(&mut results);
175let expected = [
1760x9a225cdf090f0eef6b0565d596e0512,
1770x10dd4d0bff1802930f5d5290278c2449,
1780xfefdfe067d7a109ee254a4d9392200a6,
1790xc029dc60c972179bf2f944a0eb0f21f0,
1800x2a37692ab05e660e2404c6cbc566730c,
1810xc8a72980b8c4c72a0978bb6fb279f97a,
1820xaf15ba8e302e43907dfcbb17c23b5154,
1830xa9177125baafe601560d10ef48eb5ac6,
184 ];
185assert_eq!(results, expected);
186187assert_eq!(rng.0.get_word_pos(), 32);
188 }
189190#[test]
191fn test_chacha_true_values_3() {
192// Source: Strombergson 2013, Test Vectors for the Stream Cipher ChaCha
193 // TC3: all zero key, single bit set in IV, rounds 12, 256-bit key
194195let seed = [0u8; 32];
196let mut rng = StdRng::from_seed(seed);
197 rng.0.set_stream(1);
198199let mut results = [0u128; 8];
200 rng.fill(&mut results);
201let expected = [
2020x3de08d69eff7ba6d4b8c827bf8bdb864,
2030x6929e19be5ad36988f411457633fb3f8,
2040xa5995d1de898cb9efccf8ef3a053c946,
2050xf1d8f021fb3f31ee4b9450a9a8ffced,
2060x28886a59a2b923fe42c422f2a7b49d55,
2070x23c72a9150a17ca76e8963134fee2251,
2080x67b7d07029cb2037e802f6a024bf0bf,
2090x6fa2523bbd836d3a01c8137c82b91afc,
210 ];
211assert_eq!(results, expected);
212213assert_eq!(rng.0.get_word_pos(), 32);
214 }
215216#[test]
217fn test_chacha_true_values_8() {
218// Source: Strombergson 2013, Test Vectors for the Stream Cipher ChaCha
219 // TC8: key: 'All your base are belong to us!', IV: IETF2013, rounds 12, 256-bit key
220221#[rustfmt::skip]
222let seed = [
2230xc4, 0x6e, 0xc1, 0xb1, 0x8c, 0xe8, 0xa8, 0x78,
2240x72, 0x5a, 0x37, 0xe7, 0x80, 0xdf, 0xb7, 0x35,
2250x1f, 0x68, 0xed, 0x2e, 0x19, 0x4c, 0x79, 0xfb,
2260xc6, 0xae, 0xbe, 0xe1, 0xa6, 0x67, 0x97, 0x5d,
227 ];
228let iv = [0x1a, 0xda, 0x31, 0xd5, 0xcf, 0x68, 0x82, 0x21];
229let mut rng = StdRng::from_seed(seed);
230 rng.0.set_stream(u64::from_le_bytes(iv));
231232let mut results = [0u128; 8];
233 rng.fill(&mut results);
234let expected = [
2350x10c08b11dc3be7b4066dbc8427078214,
2360xc19c7e1f25aa8669e018a96c7876793c,
2370x207c8db0992e2d24b483ee160a9a74b2,
2380xabfb0f9db3b1613b28876c46bc802b09,
2390x5495b60d624f9e9b32dbebc16b114bd9,
2400x31d66e96ad465a970c3d47689b3d8e4a,
2410x3c11e5a1df7a04d8c7ead50a53ff2ae4,
2420x2ba4a57be08f1cac89d1f183b8e3f391,
243 ];
244assert_eq!(results, expected);
245246assert_eq!(rng.0.get_word_pos(), 32);
247 }
248249#[test]
250fn test_chacha_counter() {
251// Source: rand_chacha implementation
252 // We test six blocks: counter=u32::MAX, four blocks from 2^32 (backends
253 // which yield four blocks at a time may need to handle this specially)
254 // and the first block after this wrap-logic completes.
255 // Test: all zero key and IV, block set to u32::MAX, rounds 12, 256-bit key
256257let seed = [0u8; 32];
258let mut rng = StdRng::from_seed(seed);
259let block = u32::MAX;
260let words_per_block = 16;
261 rng.0.set_word_pos((block as u128) * words_per_block);
262263let mut results = [0u128; 4 * 6];
264 rng.fill(&mut results);
265let expected = [
2660xf106e2fcbb524248292ac9f150afa6d7,
2670x12032ef6c183b50a83a3309513dd017d,
2680x2c93ff300438eaed6c958a9aa1619382,
2690x74fc0624270ab858508377945edb52d0,
2700xe5f4f4a8b8810524264d8911dc537bcc,
2710x18a6a6cbdc1f823fb1231280056740af,
2720xabdae0a44b1f45edbccc83dcd3f8638a,
2730xad6b649f12f70de567cc39740dbb8a22,
2740x37512785327825dc30ecfaf37a38f5a0,
2750x5af852d2df0dc286c2dd19af39b54e39,
2760xb04dc185c27497ac9f4a4f6769d1b5d,
2770x816492be66439cecd2498c9865284377,
2780x724fe95e0b6cbb8a55b707c06166147f,
2790xe3e7cda19d92b5318024abb34aa31329,
2800x1a3594d7283c077017cd511144bf3db3,
2810x99ab26cf14f38b11d78e413bdce6424c,
2820x553deaed89d3bf630de05408c0f655e8,
2830x86c46a5676fef18f0dc0dff3ee16507c,
2840xd33d6cf5ade97b000b29e3ce614faf51,
2850x5b62dcc48c0fc60326afc5783c40d40c,
2860x44eedc777ed030f43d382d4921eba244,
2870xa2d66a5893ade34a0d17c706e8d89dba,
2880xd229d1f3a07526e47cabd035135012fd,
2890xefae0722059b654dea6945547e535052,
290 ];
291assert_eq!(results, expected);
292293assert_eq!(rng.0.get_word_pos(), (block as u128) * words_per_block + 96);
294 }
295}