Debian Codegraph @

debian/rust-vendor/chacha20/tests/rng.rs

raw
1 //! Random number generator tests.
2
3 #![cfg(feature = "rng")]
4
5 use chacha20::{
6 ChaCha8Rng, ChaCha12Rng, ChaCha20Rng, SerializedRngState,
7 rand_core::{Rng, SeedableRng},
8 };
9 use hex_literal::hex;
10
11 const KEY: [u8; 32] = hex!("0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20");
12 const STREAM: u64 = 0xF0F1F2F3_F4F5F6F7;
13 const BLOCK_WORDS: u8 = 16;
14
15 #[test]
16 fn test_rng_output() {
17 let mut rng = ChaCha20Rng::from_seed(KEY);
18 let mut bytes = [0u8; 13];
19
20 rng.fill_bytes(&mut bytes);
21 let expected = hex!("B1697E9FC6461E1983D131CF69");
22 assert_eq!(bytes, expected);
23
24 rng.fill_bytes(&mut bytes);
25 let expected = hex!("A7A3FC134F149880E8BB2B5D23");
26 assert_eq!(bytes, expected);
27 }
28
29 #[test]
30 fn test_chacha_true_values_a() {
31 // Test vectors 1 and 2 from
32 // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
33 let seed = [0u8; 32];
34 let mut rng = ChaCha20Rng::from_seed(seed);
35
36 let mut results = [0u32; 16];
37 for i in results.iter_mut() {
38 *i = rng.next_u32();
39 }
40 let expected = [
41 0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8,
42 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815,
43 0x69b687c3, 0x8665eeb2,
44 ];
45 assert_eq!(results, expected);
46
47 for i in results.iter_mut() {
48 *i = rng.next_u32();
49 }
50 let expected = [
51 0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612,
52 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51,
53 0x1f0ae1ac, 0x6f4d794b,
54 ];
55 assert_eq!(results, expected);
56 }
57
58 #[test]
59 fn test_chacha_true_values_b() {
60 // Test vector 3 from
61 // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
62 let seed = hex!("0000000000000000000000000000000000000000000000000000000000000001");
63 let mut rng = ChaCha20Rng::from_seed(seed);
64
65 // Skip block 0
66 for _ in 0..16 {
67 rng.next_u32();
68 }
69
70 let mut results = [0u32; 16];
71 for i in results.iter_mut() {
72 *i = rng.next_u32();
73 }
74 let expected = [
75 0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, 0xe8252083, 0x60818b01, 0xf38422b8,
76 0x5aaa49c9, 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, 0x4436274e, 0x2561b3c8,
77 0xebdd4aa6, 0xa0136c00,
78 ];
79 assert_eq!(results, expected);
80 }
81
82 #[test]
83 fn test_chacha_true_values_c() {
84 // Test vector 4 from
85 // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
86 let seed = hex!("00FF000000000000000000000000000000000000000000000000000000000000");
87 let expected = [
88 0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, 0xa78dea8f, 0x5e269039, 0xa1bebbc1,
89 0xcaf09aae, 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, 0x546ca624, 0x1bec45d5,
90 0x87f47473, 0x96f0992e,
91 ];
92 let expected_end = 3 * 16;
93 let mut results = [0u32; 16];
94
95 // Test block 2 by skipping block 0 and 1
96 let mut rng1 = ChaCha20Rng::from_seed(seed);
97 for _ in 0..32 {
98 rng1.next_u32();
99 }
100 for i in results.iter_mut() {
101 *i = rng1.next_u32();
102 }
103 assert_eq!(results, expected);
104 assert_eq!(rng1.get_word_pos(), expected_end);
105
106 // Test block 2 by using `set_word_pos`
107 let mut rng2 = ChaCha20Rng::from_seed(seed);
108 rng2.set_word_pos(2 * 16);
109 for i in results.iter_mut() {
110 *i = rng2.next_u32();
111 }
112 assert_eq!(results, expected);
113 assert_eq!(rng2.get_word_pos(), expected_end);
114
115 // Test block 2 by using `set_block_pos` and u32
116 let mut rng3 = ChaCha20Rng::from_seed(seed);
117 rng3.set_block_pos(2);
118 results = [0u32; 16];
119 for i in results.iter_mut() {
120 *i = rng3.next_u32();
121 }
122 assert_eq!(results, expected);
123 assert_eq!(rng3.get_word_pos(), expected_end);
124
125 // Test block 2 by using `set_block_pos` and [u8; 8]
126 let mut rng4 = ChaCha20Rng::from_seed(seed);
127 rng4.set_block_pos(2);
128 let mut buf = [0u8; 8];
129 for chunk in expected.chunks_exact(2) {
130 rng4.fill_bytes(&mut buf);
131 assert_eq!(buf[..4], chunk[0].to_le_bytes());
132 assert_eq!(buf[4..], chunk[1].to_le_bytes());
133 }
134 assert_eq!(rng4.get_word_pos(), expected_end);
135
136 // Test skipping behaviour with other types
137 let mut buf = [0u8; 32];
138 rng2.fill_bytes(&mut buf[..]);
139 assert_eq!(rng2.get_word_pos(), expected_end + 8);
140 rng2.fill_bytes(&mut buf[0..25]);
141 assert_eq!(rng2.get_word_pos(), expected_end + 15);
142 rng2.next_u64();
143 assert_eq!(rng2.get_word_pos(), expected_end + 17);
144 rng2.next_u32();
145 rng2.next_u64();
146 assert_eq!(rng2.get_word_pos(), expected_end + 20);
147 rng2.fill_bytes(&mut buf[0..1]);
148 assert_eq!(rng2.get_word_pos(), expected_end + 21);
149 }
150
151 #[test]
152 fn test_chacha_multiple_blocks() {
153 let seed = hex!("0000000001000000020000000300000004000000050000000600000007000000");
154 let mut rng = ChaCha20Rng::from_seed(seed);
155
156 // Store the 17*i-th 32-bit word,
157 // i.e., the i-th word of the i-th 16-word block
158 let mut results = [0u32; 16];
159 for i in results.iter_mut() {
160 *i = rng.next_u32();
161 for _ in 0..16 {
162 rng.next_u32();
163 }
164 }
165 let expected = [
166 0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186,
167 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc,
168 0x5f1c86d9, 0xc1f8e7f4,
169 ];
170 assert_eq!(results, expected);
171 }
172
173 #[test]
174 fn test_chacha_true_bytes() {
175 let seed = [0u8; 32];
176 let mut rng = ChaCha20Rng::from_seed(seed);
177 let mut results = [0u8; 32];
178 rng.fill_bytes(&mut results);
179 let expected = hex!("76B8E0ADA0F13D90405D6AE55386BD28BDD219B8A08DED1AA836EFCC8B770DC7");
180 assert_eq!(results, expected);
181 }
182
183 #[test]
184 fn test_chacha_construction() {
185 let seed = hex!("0000000000000000010000000000000002000000000000000300000000000000");
186 let mut rng1 = ChaCha20Rng::from_seed(seed);
187 assert_eq!(rng1.next_u32(), 137206642);
188
189 assert_eq!(rng1.get_seed(), seed);
190
191 let mut rng2 = ChaCha20Rng::from_rng(&mut rng1);
192 assert_eq!(rng2.next_u32(), 1325750369);
193 }
194
195 #[test]
196 fn test_chacha_nonce() {
197 use hex_literal::hex;
198 // Test vector 5 from
199 // https://www.rfc-editor.org/rfc/rfc8439#section-2.3.2
200 let seed = hex!("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
201 let mut rng = ChaCha20Rng::from_seed(seed);
202
203 rng.set_stream(0x000000004a000000);
204 rng.set_block_pos(u64::from_le_bytes(hex!("0000000000000009")));
205
206 // The test vectors omit the first 64-bytes of the keystream
207 let mut discard_first_64 = [0u8; 64];
208 rng.fill_bytes(&mut discard_first_64);
209
210 let mut results = [0u32; 16];
211 for i in results.iter_mut() {
212 *i = rng.next_u32();
213 }
214 let expected = [
215 0xe4e7f110, 0x15593bd1, 0x1fdd0f50, 0xc47120a3, 0xc7f4d1c7, 0x0368c033, 0x9aaa2204,
216 0x4e6cd4c3, 0x466482d2, 0x09aa9f07, 0x05d7c214, 0xa2028bd9, 0xd19c12b5, 0xb94e16de,
217 0xe883d0cb, 0x4e3c50a2,
218 ];
219
220 assert_eq!(results, expected);
221 }
222
223 #[test]
224 fn test_chacha_nonce_2() {
225 // Test vector 5 from
226 // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
227 // Although we do not support setting a nonce, we try it here anyway so
228 // we can use this test vector.
229 let seed = [0u8; 32];
230 let mut rng = ChaCha20Rng::from_seed(seed);
231 // 96-bit nonce in LE order is: 0,0,0,0, 0,0,0,0, 0,0,0,2
232 rng.set_stream(2u64 << (24 + 32));
233
234 let mut results = [0u32; 16];
235 for i in results.iter_mut() {
236 *i = rng.next_u32();
237 }
238 let expected = [
239 0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, 0x88228b1a, 0x96a4dfb3, 0x5b76ab72,
240 0xc727ee54, 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, 0x99c28f5f, 0x628314e8,
241 0x398a19fa, 0x6ded1b53,
242 ];
243 assert_eq!(results, expected);
244 }
245
246 /// Test vector 9 from https://github.com/pyca/cryptography/blob/main/vectors/cryptography_vectors/ciphers/ChaCha20/counter-overflow.txt
247 #[test]
248 fn counter_wrap_1() {
249 let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
250 let block_pos = 18446744073709551615;
251 assert_eq!(block_pos, u64::MAX);
252 rng.set_block_pos(block_pos);
253
254 let mut output = [0u8; 64 * 3];
255 rng.fill_bytes(&mut output);
256 let expected = hex!(
257 "d7918cd8620cf832532652c04c01a553092cfb32e7b3f2f5467ae9674a2e9eec17368e"
258 "c8027a357c0c51e6ea747121fec45284be0f099d2b3328845607b1768976b8e0ada0f1"
259 "3d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d77"
260 "24e03fb8d84a376a43b8f41518a11cc387b669b2ee65869f07e7be5551387a98ba977c"
261 "732d080dcb0f29a048e3656912c6533e32ee7aed29b721769ce64e43d57133b074d839"
262 "d531ed1f28510afb45ace10a1f4b794d6f"
263 );
264 assert_eq!(expected, output);
265 }
266
267 /// Counts how many bytes were incorrect, and returns:
268 ///
269 /// (`index_of_first_incorrect_word`, `num_incorrect_bytes`)
270 fn count_incorrect_bytes(expected: &[u8], output: &[u8]) -> (Option<usize>, u32) {
271 assert_eq!(expected.len(), output.len());
272 let mut num_incorrect_bytes = 0;
273 let mut index_of_first_incorrect_word = None;
274 expected
275 .iter()
276 .enumerate()
277 .zip(output.iter())
278 .for_each(|((i, a), b)| {
279 if a.ne(b) {
280 if index_of_first_incorrect_word.is_none() {
281 index_of_first_incorrect_word = Some(i / 4);
282 }
283 num_incorrect_bytes += 1;
284 }
285 });
286 (index_of_first_incorrect_word, num_incorrect_bytes)
287 }
288
289 /// Test vector 8 from https://github.com/pyca/cryptography/blob/main/vectors/cryptography_vectors/ciphers/ChaCha20/counter-overflow.txt
290 #[test]
291 fn counter_overflow_and_diagnostics() {
292 let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
293 let block_pos = 4294967295;
294 assert_eq!(block_pos, u64::from(u32::MAX));
295 rng.set_block_pos(4294967295);
296
297 let mut output = [0u8; 64 * 4];
298 rng.fill_bytes(&mut output[..64 * 3]);
299 let block_before_overflow = hex!(
300 "ace4cd09e294d1912d4ad205d06f95d9c2f2bfcf453e8753f128765b62215f4d92c74f"
301 "2f626c6a640c0b1284d839ec81f1696281dafc3e684593937023b58b1d"
302 );
303 let first_block_after_overflow = hex!(
304 "3db41d3aa0d329285de6f225e6e24bd59c9a17006943d5c9b680e3873bdc683a581946"
305 "9899989690c281cd17c96159af0682b5b903468a61f50228cf09622b5a"
306 );
307 let second_block_after_overflow = hex!(
308 "46f0f6efee15c8f1b198cb49d92b990867905159440cc723916dc0012826981039ce17"
309 "66aa2542b05db3bd809ab142489d5dbfe1273e7399637b4b3213768aaa"
310 );
311 assert!(
312 output[..64].eq(&block_before_overflow),
313 "The first parblock was incorrect before overflow, indicating that ChaCha was not implemented correctly for this backend. Check the rounds() fn or the functions that it calls"
314 );
315
316 rng.set_block_pos(u64::from(u32::MAX) - 1);
317 let mut skipped_blocks = [0u8; 64 * 3];
318 rng.fill_bytes(&mut skipped_blocks);
319 rng.fill_bytes(&mut output[64 * 3..]);
320
321 output.chunks_exact(64).enumerate().skip(1).zip(&[first_block_after_overflow, second_block_after_overflow, second_block_after_overflow]).for_each(|((i, a), b)| {
322 let (index_of_first_incorrect_word, num_incorrect_bytes) = count_incorrect_bytes(a, b);
323 let msg = if num_incorrect_bytes == 0 {
324 "The block was correct and this will not be shown"
325 } else if num_incorrect_bytes > 32 {
326 "Most of the block was incorrect, indicating an issue with the counter using 32-bit addition towards the beginning of fn rounds()"
327 } else if num_incorrect_bytes <= 8 && matches!(index_of_first_incorrect_word, Some(12 | 13)) {
328 "When the state was added to the results/res buffer at the end of fn rounds, the counter was probably incremented in 32-bit fashion for this parblock"
329 } else {
330 // this is probably unreachable in the event of a failed assertion, but it depends on the seed
331 "Some of the block was incorrect"
332 };
333 assert!(a.eq(b), "PARBLOCK #{} uses incorrect counter addition\nDiagnostic = {}\nnum_incorrect_bytes = {}\nindex_of_first_incorrect_word = {:?}", i + 1, msg, num_incorrect_bytes, index_of_first_incorrect_word);
334 });
335 }
336
337 #[test]
338 fn test_wrapping_add() {
339 let mut rng = ChaCha20Rng::from_seed(KEY);
340 // test counter wrapping-add
341 rng.set_word_pos((1 << 68) - 65);
342 let mut output = [3u8; 1280];
343 rng.fill_bytes(&mut output);
344
345 assert_ne!(output, [0u8; 1280]);
346
347 assert!(rng.get_word_pos() < 2000);
348 assert!(rng.get_word_pos() != 0);
349 }
350
351 #[test]
352 fn test_chacha_clone_streams() {
353 let seed = [
354 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, 0,
355 0, 0,
356 ];
357 let mut rng1 = ChaCha20Rng::from_seed(seed);
358 let mut rng2 = ChaCha20Rng::from_seed(seed);
359 for _ in 0..16 {
360 assert_eq!(rng1.next_u64(), rng2.next_u64());
361 }
362
363 rng1.set_stream(51);
364 assert_eq!(rng1.get_stream(), 51);
365 assert_eq!(rng2.get_stream(), 0);
366 let mut fill_1 = [0u8; 7];
367 rng1.fill_bytes(&mut fill_1);
368 let mut fill_2 = [0u8; 7];
369 rng2.fill_bytes(&mut fill_2);
370 assert_ne!(fill_1, fill_2);
371 for _ in 0..7 {
372 assert!(rng1.next_u64() != rng2.next_u64());
373 }
374 rng2.set_stream(51); // switch part way through block
375 for _ in 7..16 {
376 assert_ne!(rng1.next_u64(), rng2.next_u64());
377 }
378 rng1.set_stream(51);
379 rng2.set_stream(51);
380 for _ in 0..16 {
381 assert_eq!(rng1.next_u64(), rng2.next_u64());
382 }
383 }
384
385 #[test]
386 fn test_chacha_word_pos_wrap_exact() {
387 let mut rng = ChaCha20Rng::from_seed(Default::default());
388 // refilling the buffer in set_word_pos will wrap the block counter to 0
389 let last_block = (1 << 68) - u128::from(4 * BLOCK_WORDS);
390 rng.set_word_pos(last_block);
391 assert_eq!(rng.get_word_pos(), last_block);
392 }
393
394 #[test]
395 fn test_chacha_word_pos_wrap_excess() {
396 let mut rng = ChaCha20Rng::from_seed(Default::default());
397 // refilling the buffer in set_word_pos will wrap the block counter past 0
398 let last_block = (1 << 68) - u128::from(BLOCK_WORDS);
399 rng.set_word_pos(last_block);
400 assert_eq!(rng.get_word_pos(), last_block);
401 }
402
403 #[test]
404 fn test_chacha_word_pos_zero() {
405 let mut rng = ChaCha20Rng::from_seed(Default::default());
406 assert_eq!(rng.get_word_pos(), 0);
407 rng.set_word_pos(0);
408 assert_eq!(rng.get_word_pos(), 0);
409 }
410
411 #[test]
412 #[allow(trivial_casts)]
413 fn test_trait_objects() {
414 use rand_core::CryptoRng;
415
416 let seed = Default::default();
417 let mut rng1 = ChaCha20Rng::from_seed(seed);
418 let rng2 = &mut ChaCha20Rng::from_seed(seed) as &mut dyn CryptoRng;
419 for _ in 0..1000 {
420 assert_eq!(rng1.next_u64(), rng2.next_u64());
421 }
422 }
423
424 /// If this test fails, the backend may not be
425 /// performing 64-bit addition.
426 #[test]
427 fn counter_wrapping_64_bit_counter() {
428 let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
429
430 // get first four blocks and word pos
431 let mut first_blocks = [0u8; 64 * 4];
432 rng.fill_bytes(&mut first_blocks);
433 let first_blocks_end_word_pos = rng.get_word_pos();
434 let first_blocks_end_block_counter = rng.get_block_pos();
435
436 // get first four blocks after wrapping
437 rng.set_block_pos(u64::MAX);
438 let mut result = [0u8; 64 * 5];
439 rng.fill_bytes(&mut result);
440 assert_eq!(first_blocks_end_word_pos, rng.get_word_pos());
441 assert_eq!(first_blocks_end_block_counter, rng.get_block_pos());
442
443 if first_blocks[0..64 * 4].ne(&result[64..]) {
444 for (i, (a, b)) in first_blocks.iter().zip(result.iter().skip(64)).enumerate() {
445 assert!(!a.ne(b), "i = {}\na = {}\nb = {}", i, a, b);
446 }
447 }
448 assert_eq!(&first_blocks[0..64 * 4], &result[64..]);
449 }
450
451 /// If this test fails, the backend may be doing 32-bit addition.
452 #[test]
453 fn counter_not_wrapping_at_32_bits() {
454 let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
455
456 // get first four blocks and word pos
457 let mut first_blocks = [0u8; 64 * 4];
458 rng.fill_bytes(&mut first_blocks);
459 let first_blocks_end_word_pos = rng.get_word_pos();
460
461 // get first four blocks after the supposed overflow
462 rng.set_block_pos(u64::from(u32::MAX));
463 let mut result = [0u8; 64 * 5];
464 rng.fill_bytes(&mut result);
465 assert_ne!(first_blocks_end_word_pos, rng.get_word_pos());
466 assert_eq!(
467 rng.get_word_pos(),
468 first_blocks_end_word_pos + (1 << 32) * u128::from(BLOCK_WORDS)
469 );
470 assert_ne!(&first_blocks[0..64 * 4], &result[64..]);
471 }
472
473 #[test]
474 fn test_chacha8rng_serde_roundtrip() {
475 for skip_words in 0..100 {
476 let mut rng = ChaCha8Rng::from_seed(KEY);
477 rng.set_stream(STREAM);
478 for _ in 0..skip_words {
479 let _ = rng.next_u32();
480 }
481 let state = rng.serialize_state();
482 let mut rng2 = ChaCha8Rng::deserialize_state(&state);
483 for _ in 0..100 {
484 assert_eq!(rng.next_u32(), rng2.next_u32());
485 }
486 }
487 }
488
489 #[test]
490 fn test_chacha12rng_serde_roundtrip() {
491 for skip_words in 0..100 {
492 let mut rng = ChaCha12Rng::from_seed(KEY);
493 rng.set_stream(STREAM);
494 for _ in 0..skip_words {
495 let _ = rng.next_u32();
496 }
497 let state = rng.serialize_state();
498 let mut rng2 = ChaCha12Rng::deserialize_state(&state);
499 for _ in 0..100 {
500 assert_eq!(rng.next_u32(), rng2.next_u32());
501 }
502 }
503 }
504
505 #[test]
506 fn test_chacha20rng_serde_roundtrip() {
507 for skip_words in 0..100 {
508 let mut rng = ChaCha20Rng::from_seed(KEY);
509 rng.set_stream(STREAM);
510 for _ in 0..skip_words {
511 let _ = rng.next_u32();
512 }
513 let state = rng.serialize_state();
514 let mut rng2 = ChaCha20Rng::deserialize_state(&state);
515 for _ in 0..100 {
516 assert_eq!(rng.next_u32(), rng2.next_u32());
517 }
518 }
519 }
520
521 #[test]
522 fn test_rng_serialized_state_stability() {
523 const EXPECTED: SerializedRngState = hex!(
524 "0102030405060708090A0B0C0D0E0F10"
525 "1112131415161718191A1B1C1D1E1F20"
526 "F7F6F5F4F3F2F1F06400000000000000"
527 "00"
528 );
529 let mut rng = ChaCha8Rng::from_seed(KEY);
530 rng.set_stream(STREAM);
531 for _ in 0..100 {
532 let _ = rng.next_u32();
533 }
534 let state = rng.serialize_state();
535 assert_eq!(state, EXPECTED);
536
537 let mut rng = ChaCha12Rng::from_seed(KEY);
538 rng.set_stream(STREAM);
539 for _ in 0..100 {
540 let _ = rng.next_u32();
541 }
542 let state = rng.serialize_state();
543 assert_eq!(state, EXPECTED);
544
545 let mut rng = ChaCha20Rng::from_seed(KEY);
546 rng.set_stream(STREAM);
547 for _ in 0..100 {
548 let _ = rng.next_u32();
549 }
550 let state = rng.serialize_state();
551 assert_eq!(state, EXPECTED);
552 }