Skip to main content

rand/rngs/
std.rs

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//! The standard RNG
10
11use chacha20::ChaCha12Rng;
12use core::convert::Infallible;
13use rand_core::{SeedableRng, TryCryptoRng, TryRng};
14
15/// 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(Debug, PartialEq, Eq)]
78pub struct StdRng(ChaCha12Rng);
79
80impl TryRng for StdRng {
81    type Error = Infallible;
82
83    #[inline(always)]
84    fn try_next_u32(&mut self) -> Result<u32, Infallible> {
85        self.0.try_next_u32()
86    }
87
88    #[inline(always)]
89    fn try_next_u64(&mut self) -> Result<u64, Infallible> {
90        self.0.try_next_u64()
91    }
92
93    #[inline(always)]
94    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Infallible> {
95        self.0.try_fill_bytes(dst)
96    }
97}
98
99impl SeedableRng for StdRng {
100    // Fix to 256 bits. Changing this is a breaking change!
101    type Seed = [u8; 32];
102
103    #[inline(always)]
104    fn from_seed(seed: Self::Seed) -> Self {
105        StdRng(ChaCha12Rng::from_seed(seed))
106    }
107}
108
109impl TryCryptoRng for StdRng {}
110
111#[cfg(test)]
112mod test {
113    use crate::rngs::StdRng;
114    use crate::{Rng, RngExt, SeedableRng};
115
116    #[test]
117    fn test_stdrng_construction() {
118        // Test value-stability of StdRng. This is expected to break any time
119        // the algorithm is changed.
120        #[rustfmt::skip]
121        let seed = [1,0,0,0, 23,0,0,0, 200,1,0,0, 210,30,0,0,
122                    0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0];
123
124        let target = [10719222850664546238, 14064965282130556830];
125
126        let mut rng0 = StdRng::from_seed(seed);
127
128        let x0 = rng0.next_u64();
129
130        let mut rng1 = StdRng::from_rng(&mut rng0);
131        let x1 = rng1.next_u64();
132
133        assert_eq!([x0, x1], target);
134    }
135
136    #[test]
137    fn 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
143
144        let seed = [0u8; 32];
145        let mut rng = StdRng::from_seed(seed);
146
147        let mut results = [0u128; 8];
148        rng.fill(&mut results);
149        let expected = [
150            0xd583265f12ce1f8153f955076a9af49b,
151            0x5f15ae2ea589007e1474e049bbc32904,
152            0x798cfaac3428e82cc0e37ad279f86405,
153            0xbe2613412fe80b611969dea02c9f623a,
154            0x3d17e08c3371fc86fe743e204188d50b,
155            0xb489c04c21851515cccbbd19b7eb28c6,
156            0x43c88c1b97b802c611f14ca1cd8d2542,
157            0x1693e617b0a64427c0515190ca461ee9,
158        ];
159        assert_eq!(results, expected);
160
161        assert_eq!(rng.0.get_word_pos(), 32);
162    }
163
164    #[test]
165    fn 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
168
169        let mut seed = [0u8; 32];
170        seed[0] = 1;
171        let mut rng = StdRng::from_seed(seed);
172
173        let mut results = [0u128; 8];
174        rng.fill(&mut results);
175        let expected = [
176            0x9a225cdf090f0eef6b0565d596e0512,
177            0x10dd4d0bff1802930f5d5290278c2449,
178            0xfefdfe067d7a109ee254a4d9392200a6,
179            0xc029dc60c972179bf2f944a0eb0f21f0,
180            0x2a37692ab05e660e2404c6cbc566730c,
181            0xc8a72980b8c4c72a0978bb6fb279f97a,
182            0xaf15ba8e302e43907dfcbb17c23b5154,
183            0xa9177125baafe601560d10ef48eb5ac6,
184        ];
185        assert_eq!(results, expected);
186
187        assert_eq!(rng.0.get_word_pos(), 32);
188    }
189
190    #[test]
191    fn 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
194
195        let seed = [0u8; 32];
196        let mut rng = StdRng::from_seed(seed);
197        rng.0.set_stream(1);
198
199        let mut results = [0u128; 8];
200        rng.fill(&mut results);
201        let expected = [
202            0x3de08d69eff7ba6d4b8c827bf8bdb864,
203            0x6929e19be5ad36988f411457633fb3f8,
204            0xa5995d1de898cb9efccf8ef3a053c946,
205            0xf1d8f021fb3f31ee4b9450a9a8ffced,
206            0x28886a59a2b923fe42c422f2a7b49d55,
207            0x23c72a9150a17ca76e8963134fee2251,
208            0x67b7d07029cb2037e802f6a024bf0bf,
209            0x6fa2523bbd836d3a01c8137c82b91afc,
210        ];
211        assert_eq!(results, expected);
212
213        assert_eq!(rng.0.get_word_pos(), 32);
214    }
215
216    #[test]
217    fn 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
220
221        #[rustfmt::skip]
222        let seed = [
223            0xc4, 0x6e, 0xc1, 0xb1, 0x8c, 0xe8, 0xa8, 0x78,
224            0x72, 0x5a, 0x37, 0xe7, 0x80, 0xdf, 0xb7, 0x35,
225            0x1f, 0x68, 0xed, 0x2e, 0x19, 0x4c, 0x79, 0xfb,
226            0xc6, 0xae, 0xbe, 0xe1, 0xa6, 0x67, 0x97, 0x5d,
227        ];
228        let iv = [0x1a, 0xda, 0x31, 0xd5, 0xcf, 0x68, 0x82, 0x21];
229        let mut rng = StdRng::from_seed(seed);
230        rng.0.set_stream(u64::from_le_bytes(iv));
231
232        let mut results = [0u128; 8];
233        rng.fill(&mut results);
234        let expected = [
235            0x10c08b11dc3be7b4066dbc8427078214,
236            0xc19c7e1f25aa8669e018a96c7876793c,
237            0x207c8db0992e2d24b483ee160a9a74b2,
238            0xabfb0f9db3b1613b28876c46bc802b09,
239            0x5495b60d624f9e9b32dbebc16b114bd9,
240            0x31d66e96ad465a970c3d47689b3d8e4a,
241            0x3c11e5a1df7a04d8c7ead50a53ff2ae4,
242            0x2ba4a57be08f1cac89d1f183b8e3f391,
243        ];
244        assert_eq!(results, expected);
245
246        assert_eq!(rng.0.get_word_pos(), 32);
247    }
248
249    #[test]
250    fn 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
256
257        let seed = [0u8; 32];
258        let mut rng = StdRng::from_seed(seed);
259        let block = u32::MAX;
260        let words_per_block = 16;
261        rng.0.set_word_pos((block as u128) * words_per_block);
262
263        let mut results = [0u128; 4 * 6];
264        rng.fill(&mut results);
265        let expected = [
266            0xf106e2fcbb524248292ac9f150afa6d7,
267            0x12032ef6c183b50a83a3309513dd017d,
268            0x2c93ff300438eaed6c958a9aa1619382,
269            0x74fc0624270ab858508377945edb52d0,
270            0xe5f4f4a8b8810524264d8911dc537bcc,
271            0x18a6a6cbdc1f823fb1231280056740af,
272            0xabdae0a44b1f45edbccc83dcd3f8638a,
273            0xad6b649f12f70de567cc39740dbb8a22,
274            0x37512785327825dc30ecfaf37a38f5a0,
275            0x5af852d2df0dc286c2dd19af39b54e39,
276            0xb04dc185c27497ac9f4a4f6769d1b5d,
277            0x816492be66439cecd2498c9865284377,
278            0x724fe95e0b6cbb8a55b707c06166147f,
279            0xe3e7cda19d92b5318024abb34aa31329,
280            0x1a3594d7283c077017cd511144bf3db3,
281            0x99ab26cf14f38b11d78e413bdce6424c,
282            0x553deaed89d3bf630de05408c0f655e8,
283            0x86c46a5676fef18f0dc0dff3ee16507c,
284            0xd33d6cf5ade97b000b29e3ce614faf51,
285            0x5b62dcc48c0fc60326afc5783c40d40c,
286            0x44eedc777ed030f43d382d4921eba244,
287            0xa2d66a5893ade34a0d17c706e8d89dba,
288            0xd229d1f3a07526e47cabd035135012fd,
289            0xefae0722059b654dea6945547e535052,
290        ];
291        assert_eq!(results, expected);
292
293        assert_eq!(rng.0.get_word_pos(), (block as u128) * words_per_block + 96);
294    }
295}