nanorand/rand/
chacha.rs
1use crate::{
2 crypto::chacha,
3 rand::{Rng, SeedableRng},
4};
5use core::fmt::{self, Debug, Display, Formatter};
6#[cfg(feature = "zeroize")]
7use zeroize::Zeroize;
8
9pub type ChaCha8 = ChaCha<8>;
11
12pub type ChaCha12 = ChaCha<12>;
14
15pub type ChaCha20 = ChaCha<20>;
17
18#[cfg_attr(feature = "zeroize", derive(Zeroize))]
22#[cfg_attr(feature = "zeroize", zeroize(drop))]
23pub struct ChaCha<const ROUNDS: u8> {
24 state: [u32; 16],
25}
26
27impl<const ROUNDS: u8> ChaCha<ROUNDS> {
28 #[must_use]
30 pub fn new() -> Self {
31 let mut key: [u8; 32] = Default::default();
32 crate::entropy::system(&mut key);
33 let mut nonce: [u8; 8] = Default::default();
34 crate::entropy::system(&mut nonce);
35 let state = chacha::chacha_init(key, nonce);
36 Self { state }
37 }
38
39 #[must_use]
41 pub const fn new_key(key: [u8; 32], nonce: [u8; 8]) -> Self {
42 let state = chacha::chacha_init(key, nonce);
43 Self { state }
44 }
45}
46
47impl<const ROUNDS: u8> Default for ChaCha<ROUNDS> {
48 fn default() -> Self {
49 let mut key: [u8; 32] = Default::default();
50 crate::entropy::system(&mut key);
51 let mut nonce: [u8; 8] = Default::default();
52 crate::entropy::system(&mut nonce);
53 let state = chacha::chacha_init(key, nonce);
54 Self { state }
55 }
56}
57
58impl<const ROUNDS: u8> Rng<64> for ChaCha<ROUNDS> {
59 fn rand(&mut self) -> [u8; 64] {
60 let block = chacha::chacha_block::<ROUNDS>(self.state);
61 let mut ret = [0_u8; 64];
62 block.iter().enumerate().for_each(|(idx, num)| {
63 let x = num.to_ne_bytes();
64 let n = idx * 4;
65 ret[n] = x[0];
66 ret[n + 1] = x[1];
67 ret[n + 2] = x[2];
68 ret[n + 3] = x[3];
69 });
70 if !chacha::chacha_increment_counter(&mut self.state) {
73 let mut new_seed: [u8; 40] = [42_u8; 40];
74 crate::entropy::system(&mut new_seed);
75 self.reseed(new_seed);
76 }
77 ret
78 }
79}
80
81impl<const ROUNDS: u8> Clone for ChaCha<ROUNDS> {
82 fn clone(&self) -> Self {
83 Self { state: self.state }
84 }
85}
86
87impl<const ROUNDS: u8> Display for ChaCha<ROUNDS> {
88 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
89 write!(f, "ChaCha ({:p}, {} rounds)", self, ROUNDS)
90 }
91}
92
93impl<const ROUNDS: u8> SeedableRng<40, 64> for ChaCha<ROUNDS> {
94 fn reseed(&mut self, seed: [u8; 40]) {
95 let mut key = [0_u8; 32];
96 let mut nonce = [0_u8; 8];
97 key.copy_from_slice(&seed[..32]);
98 nonce.copy_from_slice(&seed[32..]);
99 self.state = chacha::chacha_init(key, nonce);
100 }
101}
102
103impl<const ROUNDS: u8> Debug for ChaCha<ROUNDS> {
104 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
105 let counter = ((self.state[13] as u64) << 32) | (self.state[12] as u64);
106 f.debug_struct("ChaCha20")
107 .field("rounds", &ROUNDS)
108 .field("counter", &counter)
109 .finish()
110 }
111}