orion 0.18.1

Usable, easy and safe pure-Rust crypto
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
// MIT License

// Copyright (c) 2018-2026 The orion Developers

// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:

// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.

// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

//! # Parameters:
//! - `sk`: The secret key.
//! - `n`: The nonce value.
//! - `blockctr`: The position within the keystream.
//! - `bytes`: Bytes to apply the keystream to.
//!
//! `nonce`: "Counters and LFSRs are both acceptable ways of generating unique
//! nonces, as is encrypting a counter using a block cipher with a 64-bit block
//! size such as DES.  Note that it is not acceptable to use a truncation of a
//! counter encrypted with block ciphers with 128-bit or 256-bit blocks,
//! because such a truncation may repeat after a short time." See [RFC]
//! for more information.
//!
//! # Errors:
//! An error will be returned if:
//! - The [`ChaCha20::next_producible()`] returns err.
//! - If a keystream block (64 bytes) has been generated with [`ChaCha20::position()`] [`u32::MAX`],
//!   and [`ChaCha20::xor_keystream_into()`] is called subsequently. Generating the last keystream block
//!   moves [`ChaCha20`] into an exhausted state, which is non-resettable. In this case, the key/nonce pair
//!   has generated all possible keystream bytes and is thus not safe to use further.
//!   This can be checked with [`ChaCha20::is_exhausted()`].
//! - If [`ChaCha20::set_byte_position()`] is called with a `pos` that is equal to or greater than [`MAX_KEYSTREAM_BYTES`].
//! - If `ChaCha20::zeroize()` has been manually called outside [`Drop`] and more keystream bytes are requested.
//!   `ChaCha20::zeroize()` exhausts the state.
//!
//! # Security:
//! - It is critical for security that a given nonce is not re-used with a given
//!   key. Should this happen, the security of all data that has been encrypted
//!   with that given key is compromised.
//! - Functions herein do not provide any data integrity. If you need
//!   data integrity, which is nearly ***always the case***, you should use an
//!   AEAD construction instead. See the [`aead`](super::aead) module for this.
//! - Only a nonce for XChaCha20 is big enough to be randomly generated using a CSPRNG.
//! - To securely generate a strong key, use [`SecretKey::generate()`].
//!
//! # Recommendation:
//! - It is recommended to use [`XChaCha20Poly1305`] when possible.
//!
//! # Example:
//! ```rust
//! # #[cfg(feature = "safe_api")] {
//! use orion::hazardous::stream::chacha20::{SecretKey, Nonce, ChaCha20};
//!
//! let sk = SecretKey::generate()?;
//! // WARNING: This nonce is only meant for demonstration and should not
//! // be repeated. Please read the security section.
//! let n = Nonce::from([0u8; 12]);
//! let mut ctx = ChaCha20::new(&sk, &n);
//!
//!
//! // Encrypting a message:
//! let mut message: [u8; 15] = *b"Data to protect";
//! ctx.xor_keystream_into(&mut message)?;
//! // Decrypt (re-apply keystream):
//! ctx.set_position(0); // reset to beginning
//! ctx.xor_keystream_into(&mut message)?;
//!
//! assert_eq!("Data to protect".as_bytes(), message);
//!
//! // Seeking ahead in keystream. This example generates the 256th keystream block (64 bytes):
//! ctx.set_position(256);
//! let mut keystream_block = [0u8; 64];
//! ctx.xor_keystream_into(&mut keystream_block)?;
//!
//! # }
//! # Ok::<(), orion::errors::UnknownCryptoError>(())
//! ```
//! [`SecretKey::generate()`]: chacha20::SecretKey::generate()
//! [`XChaCha20Poly1305`]: super::aead::xchacha20poly1305
//! [`ChaCha20`]: chacha20::ChaCha20
//! [`ChaCha20::xor_keystream_into()`]: chacha20::ChaCha20::xor_keystream_into()
//! [`ChaCha20::position()`]: chacha20::ChaCha20::position()
//! [`ChaCha20::is_exhausted()`]: chacha20::ChaCha20::is_exhausted()
//! [`ChaCha20::next_producible()`]: chacha20::ChaCha20::next_producible()
//! [`ChaCha20::set_byte_position()`]: chacha20::ChaCha20::set_byte_position()
//! [`MAX_KEYSTREAM_BYTES`]: chacha20::MAX_KEYSTREAM_BYTES
//! [RFC]: https://tools.ietf.org/html/rfc8439

use crate::GenerateSecret;
use crate::errors::UnknownCryptoError;
#[cfg(feature = "safe_api")]
use crate::generics::sealed::Data;
use crate::generics::sealed::Sealed;
use crate::generics::{ByteArrayData, Public, Secret, TypeSpec};
use crate::util::endianness::load_u32_le;
use crate::util::u32x4::U32x4;
use crate::util::xor_slices;
use core::fmt::Debug;
use core::marker::PhantomData;
#[cfg(feature = "zeroize")]
use zeroize::Zeroize;

/// The key size for ChaCha20.
pub const CHACHA_KEYSIZE: usize = 32;
/// The nonce size for IETF ChaCha20.
pub const IETF_CHACHA_NONCESIZE: usize = 12;
/// The blocksize which ChaCha20 operates on.
pub const CHACHA_BLOCKSIZE: usize = 64;
/// The size of the subkey that HChaCha20 returns.
const HCHACHA_OUTSIZE: usize = 32;
/// The nonce size for HChaCha20.
pub(crate) const HCHACHA_NONCESIZE: usize = 16;
/// Maximum amount of keystream bytes that can be generated for a single key/nonce pair.
pub const MAX_KEYSTREAM_BYTES: u64 = (u32::MAX as u64 + 1) * CHACHA_BLOCKSIZE as u64;

#[derive(Debug)]
#[cfg_attr(test, derive(Clone))] // NOTE: Needed for HPKE testsuites.
/// Marker type for ChaCha20 key. See [`SecretKey`] type for convenience.
pub struct ChaCha20Key {}
impl Sealed for ChaCha20Key {}

impl ChaCha20Key {
    /// Used in HPKE generics to avoid relying on nightly const generics.
    pub(crate) const fn zero() -> Secret<Self> {
        Secret {
            data: ByteArrayData::<CHACHA_KEYSIZE> { bytes: [0u8; _] },
            _spec: PhantomData,
        }
    }
}

impl TypeSpec for ChaCha20Key {
    const NAME: &'static str = stringify!(SecretKey);
    type TypeData = ByteArrayData<CHACHA_KEYSIZE>;
}

impl From<[u8; CHACHA_KEYSIZE]> for Secret<ChaCha20Key> {
    fn from(value: [u8; CHACHA_KEYSIZE]) -> Self {
        Self::from_data(<ChaCha20Key as TypeSpec>::TypeData::from(value))
    }
}

impl GenerateSecret for ChaCha20Key {
    #[cfg(feature = "safe_api")]
    #[cfg_attr(docsrs, doc(cfg(feature = "safe_api")))]
    fn generate() -> Result<Secret<ChaCha20Key>, UnknownCryptoError> {
        let mut data = Self::TypeData::new(CHACHA_KEYSIZE)?;
        crate::util::secure_rand_bytes(&mut data.bytes)?;
        Ok(Secret::from_data(data))
    }
}

/// A type to represent the `SecretKey` that Chacha20, XChaCha20, ChaCha20-Poly1305 and
/// XChaCha20-Poly1305 use.
pub type SecretKey = Secret<ChaCha20Key>;

#[derive(Debug, Clone, Copy)]
/// Marker type for ChaCha20 nonce. See [`Nonce`] type for convenience.
pub struct ChaCha20Nonce {}
impl Sealed for ChaCha20Nonce {}

impl ChaCha20Nonce {
    /// Used in HPKE generics to avoid relyign on nightly const generics.
    pub(crate) const fn zero() -> Public<Self> {
        Public {
            data: ByteArrayData::<IETF_CHACHA_NONCESIZE> { bytes: [0u8; _] },
            _spec: PhantomData,
        }
    }
}

impl TypeSpec for ChaCha20Nonce {
    const NAME: &'static str = stringify!(Nonce);
    type TypeData = ByteArrayData<IETF_CHACHA_NONCESIZE>;
}

impl From<[u8; IETF_CHACHA_NONCESIZE]> for Public<ChaCha20Nonce> {
    fn from(value: [u8; IETF_CHACHA_NONCESIZE]) -> Self {
        Self::from_data(<ChaCha20Nonce as TypeSpec>::TypeData::from(value))
    }
}

/// A type that represents a `Nonce` that ChaCha20 and ChaCha20-Poly1305 use.
pub type Nonce = Public<ChaCha20Nonce>;

macro_rules! ROUND {
    ($r0:expr, $r1:expr, $r2:expr, $r3:expr) => {
        $r0 = $r0.wrapping_add($r1);
        $r3 = ($r3 ^ $r0).rotate_left(16);

        $r2 = $r2.wrapping_add($r3);
        $r1 = ($r1 ^ $r2).rotate_left(12);

        $r0 = $r0.wrapping_add($r1);
        $r3 = ($r3 ^ $r0).rotate_left(8);

        $r2 = $r2.wrapping_add($r3);
        $r1 = ($r1 ^ $r2).rotate_left(7);
    };
}

macro_rules! DOUBLE_ROUND {
    ($r0:expr, $r1:expr, $r2:expr, $r3:expr) => {
        ROUND!($r0, $r1, $r2, $r3);

        // Shuffle
        $r1 = $r1.shl_1();
        $r2 = $r2.shl_2();
        $r3 = $r3.shl_3();

        ROUND!($r0, $r1, $r2, $r3);

        // Unshuffle
        $r1 = $r1.shl_3();
        $r2 = $r2.shl_2();
        $r3 = $r3.shl_1();
    };
}

#[derive(Clone)]
/// IETF ChaCha20 as specified in the [RFC 8439](https://tools.ietf.org/html/rfc8439).
pub struct ChaCha20 {
    state: [U32x4; 4],
    pub(crate) keystreamblock: [u8; CHACHA_BLOCKSIZE],
    blockoffset: u8,
    streampos: u32,
    /// Flag to track if the final block counter has been used.
    /// If we didn't track, we could end up writing the same keystream
    /// block to CHACHA_BLOCKSIZE-sized output chunks over multiple
    /// xor_keystream_into() calls. As the next_producible() can
    /// only be called if more bytes that the last block is requested.
    ///
    /// This is meant to be un-resettable, because using a key/nonce pair
    /// for an exhausted stream re-generates previous keystream bytes.
    exhausted: bool,
}

impl Debug for ChaCha20 {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "{} state: {{***OMITTED***}}, keystreamblock: {{***OMITTED***}}, blockoffset: {:?}, streampos: {:?}, exhausted: {:?}",
            stringify!(ChaCha20),
            self.blockoffset,
            self.streampos,
            self.exhausted,
        )
    }
}

#[cfg(feature = "zeroize")]
impl Zeroize for ChaCha20 {
    fn zeroize(&mut self) {
        self.state.iter_mut().zeroize();
        self.keystreamblock.iter_mut().zeroize();
        self.blockoffset = 0;
        self.streampos = 0;
        // SECURITY: We've zeroed out the key, so producing any
        // further keystream would not be safe.
        self.exhausted = true;
    }
}

impl Drop for ChaCha20 {
    fn drop(&mut self) {
        #[cfg(feature = "zeroize")]
        self.zeroize();
    }
}

impl ChaCha20 {
    /// Create a new [`ChaCha20`] instance.
    pub fn new(sk: &SecretKey, n: &Nonce) -> Self {
        // Row 0 with constants.
        let r0 = U32x4(0x61707865, 0x3320646e, 0x79622d32, 0x6b206574);

        // Row 1 and 2 with secret key.
        let r1 = U32x4(
            load_u32_le(&sk.data.bytes[0..4]),
            load_u32_le(&sk.data.bytes[4..8]),
            load_u32_le(&sk.data.bytes[8..12]),
            load_u32_le(&sk.data.bytes[12..16]),
        );

        let r2 = U32x4(
            load_u32_le(&sk.data.bytes[16..20]),
            load_u32_le(&sk.data.bytes[20..24]),
            load_u32_le(&sk.data.bytes[24..28]),
            load_u32_le(&sk.data.bytes[28..32]),
        );

        let r3 = U32x4(
            0, // Default counter
            load_u32_le(&n.data.bytes[0..4]),
            load_u32_le(&n.data.bytes[4..8]),
            load_u32_le(&n.data.bytes[8..12]),
        );

        Self {
            state: [r0, r1, r2, r3],
            keystreamblock: [0u8; CHACHA_BLOCKSIZE],
            blockoffset: 0,
            streampos: 0,
            exhausted: false,
        }
    }

    /// Return `true` if the last keystream block has been generated.
    pub fn is_exhausted(&self) -> bool {
        self.exhausted
    }

    /// Check that we can produce one more keystream block, given the current state.
    ///
    /// Return error if [`Self::is_exhausted()`].
    pub fn next_producible(&self) -> Result<(), UnknownCryptoError> {
        if self.exhausted {
            Err(UnknownCryptoError)
        } else {
            Ok(())
        }
    }

    fn apply_rounds(&self) -> [U32x4; 4] {
        let mut wr0 = self.state[0];
        let mut wr1 = self.state[1];
        let mut wr2 = self.state[2];
        let mut wr3 = self.state[3];

        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);
        DOUBLE_ROUND!(wr0, wr1, wr2, wr3);

        [wr0, wr1, wr2, wr3]
    }

    /// HChaCha20 as specified in the [draft-RFC](https://github.com/bikeshedders/xchacha-rfc/blob/master).
    pub(crate) fn hchacha(sk: &SecretKey, n: &[u8; HCHACHA_NONCESIZE]) -> [u8; HCHACHA_OUTSIZE] {
        let mut ctx = ChaCha20::new(sk, &Nonce::from([0u8; IETF_CHACHA_NONCESIZE]));
        ctx.state[3] = U32x4(
            load_u32_le(&n[0..4]),
            load_u32_le(&n[4..8]),
            load_u32_le(&n[8..12]),
            load_u32_le(&n[12..16]),
        );

        #[cfg(feature = "zeroize")]
        let mut wstate = ctx.apply_rounds();
        #[cfg(not(feature = "zeroize"))]
        let wstate = ctx.apply_rounds();

        let mut out = [0u8; HCHACHA_OUTSIZE];
        wstate[0].store_into_le(&mut out[..16]);
        wstate[3].store_into_le(&mut out[16..]);

        #[cfg(feature = "zeroize")]
        wstate.iter_mut().zeroize();

        out
    }

    /// Process the next keystream and advance `self.streampos`.
    pub(crate) fn keystream_block(&mut self) {
        debug_assert!(
            !self.exhausted,
            "internally called keystream_block on an exhausted state!"
        );

        self.exhausted = self.streampos == u32::MAX;
        self.state[3].0 = self.streampos;

        let mut wstate = self.apply_rounds();

        wstate[0] = wstate[0].wrapping_add(self.state[0]);
        wstate[1] = wstate[1].wrapping_add(self.state[1]);
        wstate[2] = wstate[2].wrapping_add(self.state[2]);
        wstate[3] = wstate[3].wrapping_add(self.state[3]);

        wstate[0].store_into_le(&mut self.keystreamblock[0..16]);
        wstate[1].store_into_le(&mut self.keystreamblock[16..32]);
        wstate[2].store_into_le(&mut self.keystreamblock[32..48]);
        wstate[3].store_into_le(&mut self.keystreamblock[48..64]);

        #[cfg(feature = "zeroize")]
        wstate.iter_mut().zeroize();

        if let Some(nextpos) = self.streampos.checked_add(1) {
            self.streampos = nextpos;
        } else {
            debug_assert!(self.exhausted);
            debug_assert_eq!(self.streampos, u32::MAX);
        }
    }

    /// Given the current [`Self::byte_position`], determine how many keystream
    /// bytes can be generated from here on out. If [`Self::is_exhausted()`], then
    /// this gives `0` if no leftover.
    pub fn keystream_remaining(&self) -> u64 {
        debug_assert!((u32::MAX as u64 + 1) * (CHACHA_BLOCKSIZE as u64) < u64::MAX);
        let leftover: u64 = if self.blockoffset == 0 {
            0
        } else {
            (CHACHA_BLOCKSIZE - self.blockoffset as usize) as u64
        };

        // If the keystream is exhausted, the only possible keystream
        // left is `leftover`.
        if self.is_exhausted() {
            return leftover;
        }

        // In case there is any leftover, then we have generated
        // keystream block exactly at streampos, which has then
        // subsequently been bumped in keystream_block(), so
        // leftover is the bytes from streampos-1.
        let max: u64 = (u32::MAX as u64) + 1; // (0..=u32::MAX)
        let remblocks: u64 = max - (self.streampos as u64);
        let rembytes: u64 = remblocks * CHACHA_BLOCKSIZE as u64;

        rembytes + leftover
    }

    /// Set the position/counter of the [`ChaCha20`] state, to a specific block.
    ///
    /// # NOTE:
    /// This resets the internal offset tracker, which keeps track of unused
    /// but already generated keystream bytes, for the [`Self::position()`]
    /// prior to calling this function. To set position in terms of specific
    /// bytes across the entire keystream, use [`Self::set_byte_position`].
    ///
    /// This is equivalent to seeking ahead in the keystream output generated,
    /// on a per-block ([`CHACHA_BLOCKSIZE`]) basis.
    pub fn set_position(&mut self, blockctr: u32) {
        self.streampos = blockctr;
        self.blockoffset = 0;
        self.state[3].0 = self.streampos;
    }

    /// Set the byte position within the [`ChaCha20`] state. This will set the correct
    /// state block counter internally and any offset if needed.
    pub fn set_byte_position(&mut self, pos: u64) -> Result<(), UnknownCryptoError> {
        if pos >= MAX_KEYSTREAM_BYTES {
            return Err(UnknownCryptoError);
        }

        let block = pos / CHACHA_BLOCKSIZE as u64;
        debug_assert!((0..=u32::MAX).contains(&(block as u32)));
        let offset = pos % CHACHA_BLOCKSIZE as u64;
        debug_assert!((0..=CHACHA_BLOCKSIZE).contains(&(offset as usize)));
        self.set_position(block as u32);

        if offset > 0 {
            self.next_producible()?;

            self.keystream_block();
            self.blockoffset = offset as u8;
        }

        Ok(())
    }

    /// Get the current position/counter of the [`ChaCha20`] state, as a block.
    pub fn position(&self) -> u32 {
        self.streampos
    }

    /// Get the current position/counter of the [`ChaCha20`] state, as a byte-index.
    pub fn byte_position(&self) -> u64 {
        if self.exhausted && self.blockoffset == 0 {
            return MAX_KEYSTREAM_BYTES;
        }

        if self.blockoffset == 0 {
            return self.streampos as u64 * CHACHA_BLOCKSIZE as u64;
        }

        if self.exhausted {
            return self.streampos as u64 * CHACHA_BLOCKSIZE as u64 + self.blockoffset as u64;
        }

        (self.streampos - 1) as u64 * CHACHA_BLOCKSIZE as u64 + self.blockoffset as u64
    }

    #[must_use = "SECURITY WARNING: Ignoring a Result can have real security implications."]
    /// Produce keystream blocks, based on the [`ChaCha20::byte_position()`], and XOR into `bytes`.
    ///
    /// # SECURITY:
    /// If this returns [`UnknownCryptoError`], then not all `bytes` have been processed.
    /// Take care to zero out the bytes if this contains sensitive information.
    pub fn xor_keystream_into(&mut self, bytes: &mut [u8]) -> Result<(), UnknownCryptoError> {
        if bytes.is_empty() {
            return Ok(());
        }

        // https://github.com/orion-rs/orion/issues/308 fix was to not copy
        // plaintext into out-buffer. This new API means there's only one buffer.
        // Here `bytes` contain plaintext, so now it is user-responsibility
        // to ensure to zero out plaintext bytes if the function fails.

        let mut bytes = bytes;
        // blockoffset should never reach CHACHA_BLOCKSIZE exactly, as this indicates
        // the entire keystream has been consumed, a new one is generated and blockoffset
        // it reset to 0.
        debug_assert!((0..CHACHA_BLOCKSIZE).contains(&(self.blockoffset as usize)));

        if self.blockoffset > 0 {
            // SECURITY: This is the only time we don't check for self.exhausted/self.next_producible().
            // If the keystream is exhausted, but we enter this branch, it means we have unused keystream
            // leftover. This unused rem is safe to use. This function should only ever execute once after
            // self.exhausted == true.
            let offset = self.blockoffset as usize;
            let want = core::cmp::min(CHACHA_BLOCKSIZE - offset, bytes.len());
            xor_slices(
                &self.keystreamblock[offset..offset + want],
                &mut bytes[..want],
            );

            bytes = &mut bytes[want..];
            self.blockoffset = ((offset + want) & (CHACHA_BLOCKSIZE - 1)) as u8;
        }

        while bytes.len() >= CHACHA_BLOCKSIZE {
            self.next_producible()?;

            self.keystream_block();
            xor_slices(&self.keystreamblock, bytes);
            bytes = &mut bytes[CHACHA_BLOCKSIZE..];
        }

        if !bytes.is_empty() {
            debug_assert!(bytes.len() < CHACHA_BLOCKSIZE);
            self.next_producible()?;

            self.keystream_block();
            let offset = bytes.len();
            xor_slices(&self.keystreamblock[..offset], bytes);
            self.blockoffset = offset as u8;
        }

        Ok(())
    }
}

// Testing public functions in the module.
#[cfg(test)]
mod public {
    use super::*;
    use crate::test_framework::streamcipher_interface::*;

    const ZERO_KEY: [u8; CHACHA_KEYSIZE] = [0u8; CHACHA_KEYSIZE];
    const ZERO_IETF_NONCE: [u8; IETF_CHACHA_NONCESIZE] = [0u8; IETF_CHACHA_NONCESIZE];

    #[test]
    fn test_zerokey() {
        assert_eq!(ChaCha20Key::zero(), &ZERO_KEY);
        assert_eq!(ChaCha20Nonce::zero(), &ZERO_IETF_NONCE);
    }

    #[test]
    #[cfg(feature = "zeroize")]
    // Test to make sure that users cannot import `Zeroize` from the third-party
    // crate and manually call `.zeroize()` on [`ChaCha20`] and keep using the state
    // afterward.
    fn test_zeroize_is_exhausted() {
        let sk = SecretKey::from([0u8; CHACHA_KEYSIZE]);
        let nonce = Nonce::from(ZERO_IETF_NONCE);
        let mut buf = [0u8; CHACHA_BLOCKSIZE * 2];

        for used in [
            0,
            1,
            CHACHA_BLOCKSIZE / 2,
            CHACHA_BLOCKSIZE,
            CHACHA_BLOCKSIZE * 2,
        ] {
            let mut ctx = ChaCha20::new(&sk, &nonce);
            ctx.xor_keystream_into(&mut buf[..used]).unwrap();
            ctx.zeroize();

            // Zeroize should always exhaust the stream making it unusable.
            assert!(ctx.is_exhausted());
            assert!(ctx.next_producible().is_err());
            assert_eq!(ctx.keystream_remaining(), 0);
            assert!(ctx.xor_keystream_into(&mut buf).is_err());

            // Reset position still invalid.
            ctx.set_position(0);
            assert!(ctx.xor_keystream_into(&mut buf).is_err());
        }
    }

    #[test]
    #[cfg(feature = "safe_api")]
    // format! is only available with std
    fn test_omitted_debug() {
        let sk = SecretKey::generate().unwrap();
        let n = Nonce::from(ZERO_IETF_NONCE);
        let ctx = ChaCha20::new(&sk, &n);

        let secret_key = format!("{:?}", ctx.state);
        let secret_export = format!("{:?}", ctx.keystreamblock);

        let test_debug_contents = format!("{:?}", ctx);
        assert!(!test_debug_contents.contains(&secret_key));
        assert!(!test_debug_contents.contains(&secret_export));
    }

    #[test]
    fn test_keystream_remaining() {
        let sk = SecretKey::from(ZERO_KEY);
        let nonce = Nonce::from(ZERO_IETF_NONCE);
        let mut ctx = ChaCha20::new(&sk, &nonce);

        ctx.set_position(0);
        assert_eq!(ctx.position(), 0);
        assert_eq!(
            ctx.keystream_remaining(),
            (CHACHA_BLOCKSIZE as u64) * 2u64.pow(32)
        );

        ctx.set_position(1);
        assert_eq!(ctx.position(), 1);
        assert_eq!(
            ctx.keystream_remaining(),
            crate::hazardous::aead::chacha20poly1305::P_MAX
        );

        ctx.set_position(u32::MAX);
        assert_eq!(ctx.position(), u32::MAX);
        assert_eq!(ctx.keystream_remaining(), 64);

        // If we encrypt 1.5 block, we "forget" the rest. So this will return
        // the amount as if we encrypted two full blocks.
        let mut onehalf = [0u8; CHACHA_BLOCKSIZE + CHACHA_BLOCKSIZE / 2];
        ctx.set_position(1);
        ctx.xor_keystream_into(&mut onehalf).unwrap();
        assert_eq!(ctx.position(), 3);
        assert_eq!(
            ctx.keystream_remaining(),
            MAX_KEYSTREAM_BYTES - (CHACHA_BLOCKSIZE * 2 + CHACHA_BLOCKSIZE / 2) as u64
        );
    }

    #[test]
    fn test_chacha20_key() {
        use super::*;
        use crate::test_framework::newtypes::secret::SecretNewtype;
        SecretNewtype::test_with_generate::<
            CHACHA_KEYSIZE,
            CHACHA_KEYSIZE,
            CHACHA_KEYSIZE,
            ChaCha20Key,
        >();
    }

    #[test]
    fn test_chacha20_nonce() {
        use super::*;
        use crate::test_framework::newtypes::public::PublicNewtype;
        PublicNewtype::test_no_generate::<
            IETF_CHACHA_NONCESIZE,
            IETF_CHACHA_NONCESIZE,
            ChaCha20Nonce,
        >();

        #[cfg(feature = "serde")]
        PublicNewtype::test_serialization::<IETF_CHACHA_NONCESIZE, ChaCha20Nonce>();
    }

    impl TestableStreamCipher for ChaCha20 {
        fn _new(sk: &[u8], n: &[u8]) -> Self {
            Self::new(
                &SecretKey::try_from(sk).unwrap(),
                &Nonce::try_from(n).unwrap(),
            )
        }

        #[cfg(test)]
        #[cfg(feature = "safe_api")]
        fn _random() -> Self {
            use rand::RngExt;
            let mut rng = rand::rng();
            let rand_sk: bool = rng.random();

            let (sk, n) = if rand_sk {
                (SecretKey::generate().unwrap(), Nonce::from(ZERO_IETF_NONCE))
            } else {
                // only implemented for testing purposes.
                let mut arr = ZERO_IETF_NONCE;
                rng.fill(&mut arr);
                (SecretKey::from(ZERO_KEY), Nonce::from(arr))
            };

            Self::_new(sk.unprotected_as_ref(), n.as_ref())
        }

        fn _next_producible(&self) -> Result<(), UnknownCryptoError> {
            self.next_producible()
        }

        fn _keystream_remaining(&self) -> u64 {
            self.keystream_remaining()
        }

        fn _set_position(&mut self, blockctr: u32) {
            self.set_position(blockctr);
        }

        fn _is_exhausted(&self) -> bool {
            self.is_exhausted()
        }

        fn _position(&self) -> u32 {
            self.position()
        }

        fn _xor_keystream_into(&mut self, bytes: &mut [u8]) -> Result<(), UnknownCryptoError> {
            self.xor_keystream_into(bytes)
        }

        fn _set_byte_position(&mut self, pos: u64) -> Result<(), UnknownCryptoError> {
            self.set_byte_position(pos)
        }

        fn _byte_position(&mut self) -> u64 {
            self.byte_position()
        }

        const MAX_KEYSTREAM_BYTES: u64 = MAX_KEYSTREAM_BYTES;
    }

    #[test]
    fn test_streamcipher() {
        StreamcipherTester::<ChaCha20>::run_tests::<
            CHACHA_BLOCKSIZE,
            { u32::MAX },
            MAX_KEYSTREAM_BYTES,
        >(&ZERO_KEY, &ZERO_IETF_NONCE, None, None);
    }

    #[quickcheck]
    #[cfg(feature = "safe_api")]
    fn prop_streamcipher_interface(input: Vec<u8>) -> bool {
        let sk = SecretKey::generate().unwrap();
        let n = Nonce::from(ZERO_IETF_NONCE);
        StreamcipherTester::<ChaCha20>::run_tests::<
            CHACHA_BLOCKSIZE,
            { u32::MAX },
            MAX_KEYSTREAM_BYTES,
        >(sk.unprotected_as_ref(), n.as_ref(), Some(&input), None);

        true
    }

    #[cfg(any(feature = "safe_api", feature = "alloc"))]
    mod test_hchacha20 {
        use super::*;

        #[test]
        fn test_diff_keys_diff_output() {
            let keystream1 = ChaCha20::hchacha(&SecretKey::from(ZERO_KEY), &[0u8; 16]);
            let keystream2 = ChaCha20::hchacha(&SecretKey::from([1u8; CHACHA_KEYSIZE]), &[0u8; 16]);

            assert_ne!(keystream1, keystream2);
        }

        #[test]
        fn test_diff_nonce_diff_output() {
            let sk = SecretKey::from(ZERO_KEY);
            let keystream1 = ChaCha20::hchacha(&sk, &[0u8; 16]);
            let keystream2 = ChaCha20::hchacha(&sk, &[1u8; 16]);

            assert_ne!(keystream1, keystream2);
        }

        pub fn hchacha_test_runner(key: &str, nonce: &str, output_expected: &str) {
            let expected: [u8; HCHACHA_OUTSIZE] =
                hex::decode(output_expected).unwrap().try_into().unwrap();
            let sk = SecretKey::try_from(&hex::decode(key).unwrap()).unwrap();
            let n: [u8; HCHACHA_NONCESIZE] = hex::decode(nonce).unwrap().try_into().unwrap();

            let actual: [u8; HCHACHA_OUTSIZE] = ChaCha20::hchacha(&sk, &n);
            assert_eq!(actual, expected);
        }

        // Testing against Monocypher-generated test vectors
        // https://github.com/LoupVaillant/Monocypher/tree/master/tests/gen
        // Pulled at commit: https://github.com/LoupVaillant/Monocypher/commit/39b164a5bf715d1a62689203b059144df76d98e2

        #[test]
        fn test_case_0() {
            let key = "e4e4c4054fe35a75d9c0f679ad8770d8227e68e4c1e68ce67ee88e6be251a207";
            let nonce = "48b3753cff3a6d990163e6b60da1e4e5";
            let expected_output =
                "d805447c583fd97a07a2b7ab66be621ad0fa32d63d86ac20588da90b87c1907b";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_1() {
            let key = "d6a2df78c16c96a52d4fb01ea4ecf70e81ac001b08d6577bd91ce991c4c45c46";
            let nonce = "bc84d5465fc9139bf17042ae7313181f";
            let expected_output =
                "66d1fd5e89a564b55ccf0c339455449c20dfbc9d17081c85fbb430a157777be9";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_2() {
            let key = "7afb217bd1eceeac1e133aaa9edb441fa88ea3ae0eaa06cb9911b6d218570f92";
            let nonce = "4a70a7e992b43e0b18578e892e954c40";
            let expected_output =
                "41119e28a00a9d3f24b1910495f3058f9db83cbcf12889de84a2fcd7de8dc31b";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_3() {
            let key = "a51abdb5a85d300c32f391c45d6ef4db043ddcf4214f24ea6ef6b181071f299a";
            let nonce = "a254a4606ab6a058e0c6fb5598218db7";
            let expected_output =
                "04c2f31fdcc7013ac7d10ec82e8d3628c9ab23b08bbf95d6d77ad2dec7e865d6";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_4() {
            let key = "1deb473f7d04c152e7e857736715dc7b788aca39a3c96a878019e8999c815c57";
            let nonce = "23dbfbde05e6c71f118afc0dedb5b9f8";
            let expected_output =
                "75e9a94daf28b6b8634823325c61cdcb2beeb17a8f7554cc6d5b1b1d2e3592cf";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_5() {
            let key = "dea398b2d764bca68dfc023a9821939d389e38a072cf1b413bb1517c3fe83abe";
            let nonce = "bb1cdf3a218abb1b0c01da64c24f59ee";
            let expected_output =
                "65a20993e8e69de41d38e94c0796cb7baccd6d80a6e4084e65d0d574fbcb7311";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_6() {
            let key = "d19cfb8cb3940aba546f0be57895e2cc869fe55aab069c5abcf9e7ba6444a846";
            let nonce = "e5d73f1c8c5376c1220ff3d9d53eeb65";
            let expected_output =
                "a345f5f10ec20b4a744634fbb94e94c9425699b4d57ffeab5403b8fbfb85bae7";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_7() {
            let key = "cc53599f40d6c8348c353b00172655236cddcd1879ca1f04b35f91adab70b81f";
            let nonce = "504035fc169964a5ae985e6c11b0b7bb";
            let expected_output =
                "11dda56dce88c92641177e2a6e21b11c5ca794912b3bceb9ccb375c87bcc7968";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_8() {
            let key = "18a51fd77fbffd722aa220efdd8947ca5a5c7fb1c2ebdb9ad1f603801ff22e80";
            let nonce = "314f716af9c22022fa159dbb4b4d3153";
            let expected_output =
                "14759f0e978a9f45a4696739fecb590b4ba6f06536384225333cccba074c8a68";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_9() {
            let key = "f999b20ab4769eb1d01c057c5295ed042b4536561dce32478b113adb5b605cac";
            let nonce = "75bcfcacb5e3e811b78e72e398fdd118";
            let expected_output =
                "564eb6b2ac2b92270af7c0b054cc7a721313e4ed3651b0970db9dfcdfda27220";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_10() {
            let key = "bf04c6a7ed0756a3533e3dca02109e1830b739210bd8bffe6a8a542980bd73e9";
            let nonce = "ca43cdd4eb7173476862df6d2458d6c7";
            let expected_output =
                "4f8975d01fb3525a60de55c61190471e86b95cb3e835374d58b003f55eb9819a";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_11() {
            let key = "4739a0ad2169b9c89edd74e16fbcecc748c25dc338041fc34af0f1bda20eaf3f";
            let nonce = "ff7b372aa801eb98a1298bc610280737";
            let expected_output =
                "06ccde41d10d6466859927bfc9a476dbc84064838ec721261cb548c18bd14c67";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_12() {
            let key = "50831c8cb43cd6822bf3f6fae0801cb6c843d8066b07346635365fb7d6ee54e5";
            let nonce = "c9cd6f05d76b2bd4caec8d80b58235cb";
            let expected_output =
                "6ed040d7721395fb2c74c8afe252a169ded78e6f2f889e8fb0ec1490533a8154";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_13() {
            let key = "4268543ab0eb865a948cc5b5f6e31f05f8146bd9495acc459d6d200005ee72c3";
            let nonce = "bc3e4ae3badfd79adfe46b2ae1045f78";
            let expected_output =
                "19b839a6d3424cf2a52d301e70e76cb77368cf9f60945bf43ce4c657aeb1d157";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_14() {
            let key = "382e04c969df1a2d6a963a79c58401770a383248b5d70bb4adedcbe520fed634";
            let nonce = "f513b8c2ea6ab37fe633ba7302a5db6c";
            let expected_output =
                "fd0739819bae6c98cbde7cb50a80e8d0b359567c50cec1ca7e985745c1cedb3a";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_15() {
            let key = "2aa209e24478fa1bd6f6ffabe98555e034342cbec07364c54d1e407e282ef08e";
            let nonce = "dbfdbde936c9d42df58ae15889f5c939";
            let expected_output =
                "f5047baa0acf9a603415a09b64268d77712ae902c73490e9c53db593765726db";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_16() {
            let key = "a3087eaeac1f2a58e2c2763d01b55744c4a65f4db93adff0078c63f090fb607a";
            let nonce = "90c87defd622e5f55977877cec9ed883";
            let expected_output =
                "1d882fa80248882c6bc311a693ebd06b8c09aa2776e6e90df523d12bfeeed77a";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_17() {
            let key = "12b0411228540cd6dde6e84cd2da59b1871db119e3298e3c12fe8200a47eddf0";
            let nonce = "49c971cd99f694e3b2a5e25fa37aedf0";
            let expected_output =
                "69bb83ccb7bc4deaf60cfe168cb11fad4257222c3523c2d08922564ac0fb74d2";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_18() {
            let key = "1bf32e7c679a3187e22a635d301ce98ad000ca301049f2e891e403250c3358fc";
            let nonce = "2030b227bb96e93b88f419afe9f9d660";
            let expected_output =
                "d0ed414a875a81db1e4cff7609afdbb2ffcdd575ebc17543fb92de53c6487efb";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_19() {
            let key = "e013761228051ec5a8f0c093b33fc60e2cd7a9c845434e95d4319d79d1bdaa8f";
            let nonce = "73853fbd9958e9ffc23a0ecbb7b48dbb";
            let expected_output =
                "e3f6c6da6c0300103d665dd877a8b62e23b1361bf3af5bbc2310502131d69be8";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_20() {
            let key = "a63672d582bb83d92249800324cbc9a6e5b37d36887e7c79093f58ef8f1a0015";
            let nonce = "85321bfee1714260dd6130cc768d20b1";
            let expected_output =
                "97e05360aca70058389d93be38d49fa26df01a4d3b4c4f10c3ec31e0ed64f08e";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_21() {
            let key = "4d3850f0eec0f8f349110e751c16cdb5ed05516df17479937d942c90eb1fb181";
            let nonce = "3062bd3f3f6b7668cd8fd3afce0cc752";
            let expected_output =
                "77513195542b2ab157cb2e6870c5b1ba143a8423ad276a64152ab923c6f54c06";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_22() {
            let key = "9b87dfc58eceb951e1e53d9e94793329199c42d004bc0f0dab3adf0cd702e99e";
            let nonce = "fa5ef6e59d3b201680f8e2d5a4ef7f23";
            let expected_output =
                "56a208bd87c5b486b5de50fbe4c1c476532f874147eba529cbb0cbeae8f09b94";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_23() {
            let key = "f1b6a8e102670a3829a995ae23fbc3a5639e028cd2b5f71bb90c7a1e4a8a0501";
            let nonce = "7d26e3afc3a88541f6c3f45d71f8a3cc";
            let expected_output =
                "a02140057f889e7ab36b4a5066e376dff248d13bd8072c384e23bd8fe4bf7047";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_24() {
            let key = "31a063ea4aad1b4d00db6f5228e9b9b1561a7f61812b8b79e6af4292580d02ea";
            let nonce = "4f6266d04244303304510272e383eaa5";
            let expected_output =
                "d610d44b8b3c14c7d3782f73405637fd14b7fada717665a9acbd4df6daa89adc";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_25() {
            let key = "1a8ea7099a74bafa3375b210653a0d2f40b15afd725cf5065066be1cb803dc15";
            let nonce = "8865ed8d7cca72dcf2b7c6b5d0d045bf";
            let expected_output =
                "f10cce296197a056bedbee166183ad6aaa56bdb21c3459296ca54c0bb78317d1";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_26() {
            let key = "32b063d3da484ba1843e071b61c49ce7f30ba18a4f7ef2730ecd785494839966";
            let nonce = "f593168e17311913753c59593fc66cb6";
            let expected_output =
                "f18115a9568724c25184728f563b65b737219cb0df1b3ce19a8bdcbdf7b8b2be";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_27() {
            let key = "64c1572251132fc28bf37fd8e96f2327cf7948a1126fd37175a91f483d6b3ad9";
            let nonce = "2308df7e6daa8bf3efde75f80ad72a49";
            let expected_output =
                "06a24cb90abe94cf3ee8e429d8197bc42bc769fbe81119156274f9692aa017a2";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_28() {
            let key = "ae0794009e21ad33fa4141fe5fa79fed12f6a20f51614dc130f45598e92549b1";
            let nonce = "13ed6185724507e7fa5a7e8a75b2c7a3";
            let expected_output =
                "51d1aec8d64d20e448a377bfa83ccbf71a73a3ad00d062bf6b83c549a7296ef1";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_29() {
            let key = "ad700919f36a46ea0ffa680857e30188f8a03c7c4b6c11bc39aececec2668723";
            let nonce = "3682d31887277028e2fd286f2654c681";
            let expected_output =
                "a24610a94968df2dc9d197cd0bc55cab08c9dabd444c0efcd2a47fd37016382e";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_30() {
            let key = "efd9e7ed6b340874e897337d4dcc672811a6cf4b69086e0a57c266424dc1d10e";
            let nonce = "cbaf0c822cce9e4f17b19e0ece39c180";
            let expected_output =
                "6f94a0f8ed7f3fe5ebaa3b8caba016ab64373ffc3c7b1c86e6787f31b4a905ec";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_31() {
            let key = "a4c756c03c19900280ff6cdebe5174d507c6e0860c38c3537176c58965b74a56";
            let nonce = "c52b3151bb8a149cf4f82158d57c823f";
            let expected_output =
                "50ea3d4f6a45e4a062b2d966e63cac51e093dfb6ab9df6d16bb109bc177b0a38";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_32() {
            let key = "3a90c6b427912226ff604d9abee1fb8c8d35530a0cd5808e53e308ac580f7318";
            let nonce = "fe2ab2a4933b5d90db718aa3440fbe9b";
            let expected_output =
                "2b57adcc5d26060383c87ef7e055f9aca4addcb2646cbf2cff4edc3f17b72ad5";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_33() {
            let key = "a17f09716219bdffc93a189e410a6a3e6477fbb05c7c35956c3c0c5f342355fa";
            let nonce = "0850307998642501c025e3873ebac3cc";
            let expected_output =
                "d3a58c49e9fe1ecf2eca169f4d4131cde27279053d562d0429a08ec701aaa39e";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_34() {
            let key = "d749d8379ae6d830f785ec104897bd723d34ad20c9d36bfe371df46aebc6d459";
            let nonce = "5d490a770bee4dd0be6a5a0b5e95645c";
            let expected_output =
                "c278c0079bd656f1dadf3dec692f19f25339c6557542181716d2a41379740bf2";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_35() {
            let key = "7dcbc03c27010df3320fe75b0a3ecc8983ad94217e80348fd0f3f54e54b95bb5";
            let nonce = "48dc2225a264443732b41b861590358d";
            let expected_output =
                "b244c408c74f3dcb8bcb72f834a054c554edad0363d761847003dab003ac6848";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_36() {
            let key = "543894006b73f3d70fc04b15d0c2a5dfa650be5044fb5061811b866be7f9d623";
            let nonce = "fcb077ee19421610aeb263c57faef006";
            let expected_output =
                "fb20ea177cb7225c87122f285d92faf0c2033e2497575f74505255b6d3dfcb96";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_37() {
            let key = "62d424c07a7aa5005068b262251c0667a4e2e4b12f5df7f509564517887e370b";
            let nonce = "425fabab1ce9e733ab2911b42074414e";
            let expected_output =
                "3a5eb5552cdd267c05c1e4fe936ce8f0eaf7279ff328ed9a42d6d83f7b30416c";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_38() {
            let key = "387d7247fa5055489bbd4b7d4de256de723566c1c2d3ecee8c10e7d98233dbef";
            let nonce = "90494951ec91a843f6701f8216a7326b";
            let expected_output =
                "8c4bc60a1e05004ec93aef4ae162aeff43d679ea1ba048739c700d6a168bc6cc";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_39() {
            let key = "241fd57f32e09976de4054797b9aee820e0de381d02852ac13f511918267b703";
            let nonce = "7330e60ba1c5875a0275f8ccc75cbe98";
            let expected_output =
                "9e724c5b0321e2528278a501108f1ae8a14dffaea9b6b138eacef3bd8d4dda41";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_40() {
            let key = "7c12457eb5614f87f1fdc40118906d02c602059d48ae05ae62d3d607d6bf63c6";
            let nonce = "760b802483b0e3aaa9dd4f79c6c5e93e";
            let expected_output =
                "e5b86f76fbc1f488c44e4d7f304736b752ab6cfb99fcf6910668eeefa4b67c2a";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_41() {
            let key = "6b51da45018c6bde108f81f9abfa23640b83cfe3fed34bcf6640bf0baf647daf";
            let nonce = "e9bc99acee972b5a152efa3e69e50f34";
            let expected_output =
                "1032b5d539b1c8cd6e0be96db443a08fc759bea8988384435c03b5f00b6e485f";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_42() {
            let key = "3bc12887fec8e70db73b4b48dce564d83786aca4c6b7e224163ea928771fde37";
            let nonce = "78c453b35d98deced812fc5685843565";
            let expected_output =
                "2279b063dab4c73a96abe02175e694662c65d09eb5889234293c7a1f2911e13d";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_43() {
            let key = "b73d097601d3558278bd9d7327de5fdaa2b842050b370e837ef811a496169d5f";
            let nonce = "f768878766c08c45561fdc2aad6469c1";
            let expected_output =
                "a8e85a6ab627f08ad415649a9cf9998f4b1065030f3c844e31c8185036af7558";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_44() {
            let key = "1380c3d3f873c7233c541ea4c43824ecd8bf7e11ac8486208fb685218d46736e";
            let nonce = "51103d1fae0e8e368f25480ee7328381";
            let expected_output =
                "9b84e50804449b594a54240741e21d75d31050d2612f4cbc651fea2f25bd9c1f";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_45() {
            let key = "c2f8b252a18a29c44dbfbb62cbe6c3dfd4db55378734d8110b8f20f1d1ada6dd";
            let nonce = "d4da48fb09c06580eb46bbc5ca62bfab";
            let expected_output =
                "315c3fe1009e438762a72f27e7a68b8ccb2c0b60bf79cb6e48123db0c42d4aeb";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_46() {
            let key = "40b184271b73b710d40cb63435042c9b526d1e5c3a77bfc516a2bcb4cc27ecae";
            let nonce = "b3451318590c84e311dd1e876f527d81";
            let expected_output =
                "cbbde3a3412504c1f684aa273ee691159edc9f44e306360278d63d4ee2f1faa4";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_47() {
            let key = "ec81df06c7e426b729aebb02be30c846eb228490df4a0e6c688aaaa6bf05d144";
            let nonce = "28335f2652926bfdfe32dfd789173ba8";
            let expected_output =
                "522b522e4cf9aa1e80126a446ed7b9665af3e781a3d5afdce43a5fe0cdbd4351";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_48() {
            let key = "60fa0114802ee333d7c49ccaad8108db470c882514716592e57aba26bb75049b";
            let nonce = "75db088bd1a89c6a67fb76b96c987478";
            let expected_output =
                "e004cc12dfdb74268e59958385e2a1c6ff31e31664838971629f5bbf88f4ed51";
            hchacha_test_runner(key, nonce, expected_output);
        }
        #[test]
        fn test_case_49() {
            let key = "bfba2449a607f3cca1c911d3b7d9cb972bcd84b0246189c7820032e031949f1e";
            let nonce = "97e8ad5eb5a75cc805900850969de48e";
            let expected_output =
                "19faebfbb954552fcfbf9b91f271c9397a15c641733c394a9cb731c286c68645";
            hchacha_test_runner(key, nonce, expected_output);
        }
    }
}

// Testing private functions in the module.
#[cfg(test)]
mod private {
    use super::*;

    const ZERO_KEY: [u8; CHACHA_KEYSIZE] = [0u8; CHACHA_KEYSIZE];
    const ZERO_IETF_NONCE: [u8; IETF_CHACHA_NONCESIZE] = [0u8; IETF_CHACHA_NONCESIZE];

    mod test_xor_keystream_into {
        use super::*;

        #[test]
        fn test_xor_keystream_ok_empty_input() {
            let mut ctx = ChaCha20::new(&SecretKey::from(ZERO_KEY), &Nonce::from(ZERO_IETF_NONCE));
            let mut out = [0u8; 0];
            assert!(ctx.xor_keystream_into(&mut out).is_ok());
        }
    }

    mod test_keystream_block {
        use super::*;

        #[test]
        fn test_xor_keystream_err_on_too_much_keystream_data_ietf() {
            let mut chacha_state_ietf = ChaCha20 {
                state: [
                    U32x4(0, 0, 0, 0),
                    U32x4(0, 0, 0, 0),
                    U32x4(0, 0, 0, 0),
                    U32x4(0, 0, 0, 0),
                ],
                keystreamblock: [0u8; CHACHA_BLOCKSIZE],
                blockoffset: 0u8,
                streampos: (u32::MAX - 128),
                exhausted: false,
            };

            // xor_keystream_into() logic is tested with: StreamcipherTester::last_keystream_block_exhausts().

            assert_eq!(chacha_state_ietf.position(), u32::MAX - 128);
            assert_eq!(
                chacha_state_ietf.keystream_remaining(),
                (u32::MAX - chacha_state_ietf.position() + 1) as u64 * CHACHA_BLOCKSIZE as u64
            );

            for block_n in 0..=128 {
                if block_n == 128 {
                    assert!(!chacha_state_ietf.is_exhausted());
                    assert_eq!(chacha_state_ietf.position(), u32::MAX);

                    chacha_state_ietf.keystream_block();

                    assert!(chacha_state_ietf.is_exhausted());
                    assert_eq!(chacha_state_ietf.position(), u32::MAX);
                } else {
                    chacha_state_ietf.keystream_block();
                }
            }
        }

        #[test]
        #[cfg(debug_assertions)]
        #[should_panic]
        fn test_panic_debug_calling_keystream_block_on_exhausted() {
            let mut chacha_state = ChaCha20 {
                state: [
                    U32x4(0, 0, 0, 0),
                    U32x4(0, 0, 0, 0),
                    U32x4(0, 0, 0, 0),
                    U32x4(0, 0, 0, 0),
                ],
                keystreamblock: [0u8; CHACHA_BLOCKSIZE],
                blockoffset: 0u8,
                streampos: (u32::MAX - 2),
                exhausted: false,
            };

            chacha_state.keystream_block();
            chacha_state.keystream_block();
            chacha_state.keystream_block();

            // debug_assert! fails:
            chacha_state.keystream_block();
        }
    }
}

// Testing any test vectors that aren't put into library's /tests folder.
#[cfg(test)]
mod test_vectors {
    use super::*;

    // NOTE: These PartialEq implementation should only be available in testing.
    #[cfg(test)]
    impl PartialEq for U32x4 {
        fn eq(&self, other: &Self) -> bool {
            self.0 == other.0 && self.1 == other.1 && self.2 == other.2 && self.3 == other.3
        }
    }

    #[test]
    fn rfc8439_chacha20_block_results() {
        let key = [
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
            0x1c, 0x1d, 0x1e, 0x1f,
        ];
        let nonce = [
            0x00, 0x00, 0x00, 0x09, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x00, 0x00,
        ];
        let expected = [
            0x10, 0xf1, 0xe7, 0xe4, 0xd1, 0x3b, 0x59, 0x15, 0x50, 0x0f, 0xdd, 0x1f, 0xa3, 0x20,
            0x71, 0xc4, 0xc7, 0xd1, 0xf4, 0xc7, 0x33, 0xc0, 0x68, 0x03, 0x04, 0x22, 0xaa, 0x9a,
            0xc3, 0xd4, 0x6c, 0x4e, 0xd2, 0x82, 0x64, 0x46, 0x07, 0x9f, 0xaa, 0x09, 0x14, 0xc2,
            0xd7, 0x05, 0xd9, 0x8b, 0x02, 0xa2, 0xb5, 0x12, 0x9c, 0xd1, 0xde, 0x16, 0x4e, 0xb9,
            0xcb, 0xd0, 0x83, 0xe8, 0xa2, 0x50, 0x3c, 0x4e,
        ];

        let expected_init = [
            U32x4(0x61707865, 0x3320646e, 0x79622d32, 0x6b206574),
            U32x4(0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c),
            U32x4(0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c),
            U32x4(0x00000001, 0x09000000, 0x4a000000, 0x00000000),
        ];
        // Test initial key-setup
        let mut state = ChaCha20::new(&SecretKey::from(key), &Nonce::from(nonce));
        state.set_position(1);
        assert_eq!(state.state, expected_init);

        state.keystream_block();
        assert_eq!(state.keystreamblock, expected);
    }

    #[test]
    fn rfc8439_chacha20_block_test_1() {
        let key = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];
        let nonce = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let expected = [
            0x76, 0xb8, 0xe0, 0xad, 0xa0, 0xf1, 0x3d, 0x90, 0x40, 0x5d, 0x6a, 0xe5, 0x53, 0x86,
            0xbd, 0x28, 0xbd, 0xd2, 0x19, 0xb8, 0xa0, 0x8d, 0xed, 0x1a, 0xa8, 0x36, 0xef, 0xcc,
            0x8b, 0x77, 0x0d, 0xc7, 0xda, 0x41, 0x59, 0x7c, 0x51, 0x57, 0x48, 0x8d, 0x77, 0x24,
            0xe0, 0x3f, 0xb8, 0xd8, 0x4a, 0x37, 0x6a, 0x43, 0xb8, 0xf4, 0x15, 0x18, 0xa1, 0x1c,
            0xc3, 0x87, 0xb6, 0x69, 0xb2, 0xee, 0x65, 0x86,
        ];

        let mut state = ChaCha20::new(&SecretKey::from(key), &Nonce::from(nonce));
        state.set_position(0);
        state.keystream_block();
        assert_eq!(state.keystreamblock, expected);
    }

    #[test]
    fn rfc8439_chacha20_block_test_2() {
        let key = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];
        let nonce = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let expected = [
            0x9f, 0x07, 0xe7, 0xbe, 0x55, 0x51, 0x38, 0x7a, 0x98, 0xba, 0x97, 0x7c, 0x73, 0x2d,
            0x08, 0x0d, 0xcb, 0x0f, 0x29, 0xa0, 0x48, 0xe3, 0x65, 0x69, 0x12, 0xc6, 0x53, 0x3e,
            0x32, 0xee, 0x7a, 0xed, 0x29, 0xb7, 0x21, 0x76, 0x9c, 0xe6, 0x4e, 0x43, 0xd5, 0x71,
            0x33, 0xb0, 0x74, 0xd8, 0x39, 0xd5, 0x31, 0xed, 0x1f, 0x28, 0x51, 0x0a, 0xfb, 0x45,
            0xac, 0xe1, 0x0a, 0x1f, 0x4b, 0x79, 0x4d, 0x6f,
        ];

        let mut state = ChaCha20::new(&SecretKey::from(key), &Nonce::from(nonce));
        state.set_position(1);
        state.keystream_block();
        assert_eq!(state.keystreamblock, expected);
    }

    #[test]
    fn rfc8439_chacha20_block_test_3() {
        let key = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x01,
        ];
        let nonce = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let expected = [
            0x3a, 0xeb, 0x52, 0x24, 0xec, 0xf8, 0x49, 0x92, 0x9b, 0x9d, 0x82, 0x8d, 0xb1, 0xce,
            0xd4, 0xdd, 0x83, 0x20, 0x25, 0xe8, 0x01, 0x8b, 0x81, 0x60, 0xb8, 0x22, 0x84, 0xf3,
            0xc9, 0x49, 0xaa, 0x5a, 0x8e, 0xca, 0x00, 0xbb, 0xb4, 0xa7, 0x3b, 0xda, 0xd1, 0x92,
            0xb5, 0xc4, 0x2f, 0x73, 0xf2, 0xfd, 0x4e, 0x27, 0x36, 0x44, 0xc8, 0xb3, 0x61, 0x25,
            0xa6, 0x4a, 0xdd, 0xeb, 0x00, 0x6c, 0x13, 0xa0,
        ];

        let mut state = ChaCha20::new(&SecretKey::from(key), &Nonce::from(nonce));
        state.set_position(1);
        state.keystream_block();
        assert_eq!(state.keystreamblock, expected);
    }

    #[test]
    fn rfc8439_chacha20_block_test_4() {
        let key = [
            0x00, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];
        let nonce = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
        ];
        let expected = [
            0x72, 0xd5, 0x4d, 0xfb, 0xf1, 0x2e, 0xc4, 0x4b, 0x36, 0x26, 0x92, 0xdf, 0x94, 0x13,
            0x7f, 0x32, 0x8f, 0xea, 0x8d, 0xa7, 0x39, 0x90, 0x26, 0x5e, 0xc1, 0xbb, 0xbe, 0xa1,
            0xae, 0x9a, 0xf0, 0xca, 0x13, 0xb2, 0x5a, 0xa2, 0x6c, 0xb4, 0xa6, 0x48, 0xcb, 0x9b,
            0x9d, 0x1b, 0xe6, 0x5b, 0x2c, 0x09, 0x24, 0xa6, 0x6c, 0x54, 0xd5, 0x45, 0xec, 0x1b,
            0x73, 0x74, 0xf4, 0x87, 0x2e, 0x99, 0xf0, 0x96,
        ];

        let mut state = ChaCha20::new(&SecretKey::from(key), &Nonce::from(nonce));
        state.set_position(2);
        state.keystream_block();
        assert_eq!(state.keystreamblock, expected);
    }

    #[test]
    fn rfc8439_chacha20_block_test_5() {
        let key = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
            0x00, 0x00, 0x00, 0x00,
        ];
        let nonce = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,
        ];
        let expected = [
            0xc2, 0xc6, 0x4d, 0x37, 0x8c, 0xd5, 0x36, 0x37, 0x4a, 0xe2, 0x04, 0xb9, 0xef, 0x93,
            0x3f, 0xcd, 0x1a, 0x8b, 0x22, 0x88, 0xb3, 0xdf, 0xa4, 0x96, 0x72, 0xab, 0x76, 0x5b,
            0x54, 0xee, 0x27, 0xc7, 0x8a, 0x97, 0x0e, 0x0e, 0x95, 0x5c, 0x14, 0xf3, 0xa8, 0x8e,
            0x74, 0x1b, 0x97, 0xc2, 0x86, 0xf7, 0x5f, 0x8f, 0xc2, 0x99, 0xe8, 0x14, 0x83, 0x62,
            0xfa, 0x19, 0x8a, 0x39, 0x53, 0x1b, 0xed, 0x6d,
        ];

        let mut state = ChaCha20::new(&SecretKey::from(key), &Nonce::from(nonce));
        state.set_position(0);
        state.keystream_block();
        assert_eq!(state.keystreamblock, expected);
    }

    #[test]
    fn rfc8439_key_schedule() {
        let key = [
            0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
            0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
            0x1c, 0x1d, 0x1e, 0x1f,
        ];
        let nonce = [
            0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x4a, 0x00, 0x00, 0x00, 0x00,
        ];
        // First block setup expected
        let first_state = [
            U32x4(0x61707865, 0x3320646e, 0x79622d32, 0x6b206574),
            U32x4(0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c),
            U32x4(0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c),
            U32x4(0x00000001, 0x00000000, 0x4a000000, 0x00000000),
        ];
        // Second block setup expected
        let second_state = [
            U32x4(0x61707865, 0x3320646e, 0x79622d32, 0x6b206574),
            U32x4(0x03020100, 0x07060504, 0x0b0a0908, 0x0f0e0d0c),
            U32x4(0x13121110, 0x17161514, 0x1b1a1918, 0x1f1e1d1c),
            U32x4(0x00000002, 0x00000000, 0x4a000000, 0x00000000),
        ];

        // Expected keystream
        let expected_keystream = [
            0x22, 0x4f, 0x51, 0xf3, 0x40, 0x1b, 0xd9, 0xe1, 0x2f, 0xde, 0x27, 0x6f, 0xb8, 0x63,
            0x1d, 0xed, 0x8c, 0x13, 0x1f, 0x82, 0x3d, 0x2c, 0x06, 0xe2, 0x7e, 0x4f, 0xca, 0xec,
            0x9e, 0xf3, 0xcf, 0x78, 0x8a, 0x3b, 0x0a, 0xa3, 0x72, 0x60, 0x0a, 0x92, 0xb5, 0x79,
            0x74, 0xcd, 0xed, 0x2b, 0x93, 0x34, 0x79, 0x4c, 0xba, 0x40, 0xc6, 0x3e, 0x34, 0xcd,
            0xea, 0x21, 0x2c, 0x4c, 0xf0, 0x7d, 0x41, 0xb7, 0x69, 0xa6, 0x74, 0x9f, 0x3f, 0x63,
            0x0f, 0x41, 0x22, 0xca, 0xfe, 0x28, 0xec, 0x4d, 0xc4, 0x7e, 0x26, 0xd4, 0x34, 0x6d,
            0x70, 0xb9, 0x8c, 0x73, 0xf3, 0xe9, 0xc5, 0x3a, 0xc4, 0x0c, 0x59, 0x45, 0x39, 0x8b,
            0x6e, 0xda, 0x1a, 0x83, 0x2c, 0x89, 0xc1, 0x67, 0xea, 0xcd, 0x90, 0x1d, 0x7e, 0x2b,
            0xf3, 0x63,
        ];

        let mut state = ChaCha20::new(&SecretKey::from(key), &Nonce::from(nonce));
        let mut actual_keystream = [0u8; 128];

        state.set_position(1);
        state
            .xor_keystream_into(&mut actual_keystream[..64])
            .unwrap();
        assert!(first_state == state.state);

        state.set_position(2);
        state
            .xor_keystream_into(&mut actual_keystream[64..])
            .unwrap();
        assert!(second_state == state.state);

        assert_eq!(
            actual_keystream[..expected_keystream.len()].as_ref(),
            expected_keystream.as_ref()
        );
    }
}