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
/*
This is part of WHY2
Copyright (C) 2022-2026 Václav Šmejkal
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
//! # REX Crypto Utilities
//!
//! Provides key derivation, round key expansion, and CTR mode application
//! for the WHY2 encryption system.
use ;
use
;
use
;
use
;
use Zeroizing;
use crate::
;
/// Computes a SHA-256 hash of the Grid contents to produce a deterministic seed.
///
/// This function serializes the grid into big-endian bytes and feeds them into a SHA-256
/// hasher. The resulting 32-byte digest can be used as a seed for shuffling, masking, or
/// round-dependent randomness in the WHY2 cipher.
///
/// # Parameters
/// - `key`: A `Grid` reference whose contents will be hashed.
///
/// # Returns
/// A `[u8; 32]` array containing the SHA-256 digest of the grid.
///
/// # Notes
/// - The hash is computed in row-major order.
/// - Each `i64` cell is encoded using big-endian byte order.
/// - This method is deterministic and does not use any external randomness.
/// Generates a deterministic key vector using a ChaCha20-based DRNG.
///
/// This function produces a `Vec<i64>` of length $2 \times W \times H$ by sampling from
/// the provided ChaCha20 random number generator. Each value is derived from a
/// `u64` output and cast to `i64`.
///
/// # Parameters
/// - `rng`: A mutable reference to a seeded [`ChaCha20Rng`] instance.
///
/// # Returns
/// A vector of signed 64-bit integers representing raw key material.
///
/// # Notes
/// - The output is deterministic for a given RNG seed.
/// Generates a symmetric WHY2 key using secure system entropy.
///
/// This function creates a 32-byte seed using [`SysRng`], then initializes
/// a [`ChaCha20Rng`] with that seed to produce a deterministic
/// stream of pseudorandom values. The output is a flat `Vec<i64>` of length $2 \times W \times H$,
/// suitable for use with [`Grid::from_key`](crate::grid::Grid::from_key).
///
/// # Returns
/// A vector of signed 64-bit integers representing raw symmetric key material.
///
/// # Notes
/// - The key is generated using system entropy and is cryptographically secure.
/// - The output is deterministic for the derived seed, but the seed itself is random.
/// - This method is suitable for one-time key generation in encryption workflows.
/// Derives a sequence of round keys from a master Grid using a deterministic CSPRNG stream.
///
/// This function generates [`consts::ROUND_KEYS`] round keys by expanding the master key
/// using a CSPRNG stream.
///
/// $$ S = \text{Hash}(\text{MasterKey}) $$
/// $$ K_0, \dots, K_N \leftarrow \text{CSPRNG}(S) $$
///
/// The master key hash is used as a seed for a [`ChaCha20Rng`], which produces a continuous
/// stream of `i64` values. These are then converted into `Grid` instances using
/// [`Grid::from_key`](crate::grid::Grid::from_key).
///
/// # Parameters
/// - `master_key`: The initial Grid used to seed the key generation.
///
/// # Returns
/// A vector of `Grid` round keys, derived deterministically from the master key.
///
/// # Notes
/// - The CSPRNG is initialized once using the `master_key` hash.
/// - All keys are generated from a single stream, acting as a KDF-Expand phase.
/// - This method ensures reproducible round key generation without external randomness.
/// Generates a random nonce for CTR mode.
///
/// This creates a single Grid filled with cryptographically secure random values
/// using system entropy. The nonce must be unique for each encryption session.
///
/// # Returns
/// A Grid suitable for use as a CTR nonce.
///
/// # Errors
/// Returns an error if the Grid dimensions are invalid (should never happen in practice).
///
/// # Notes
/// - The nonce does not need to be secret, but must be strictly unique per message.
/// - The nonce will be transmitted alongside the ciphertext.
/// Applies CTR (Counter) mode encryption/decryption in parallel.
///
/// This function transforms the input `grids` in-place by XORing them with a generated
/// keystream. Because CTR mode is symmetric, this function is utilized for both encryption
/// and decryption logic.
///
/// # Overview
/// For each grid block $G_i$ at index $i$, the transformation is defined as:
///
/// $$ G_i \leftarrow G_i \oplus E_K(\text{Nonce} + \text{offset} + i) $$
///
/// Where $E_K$ denotes the WHY2 block cipher keyed with the provided `round_keys`.
/// The block counter is computed by adding the global `counter_offset` and the local
/// index $i$ to the base `nonce` using wrapping arithmetic.
///
/// # Parallelism
/// This function utilizes [`rayon`] to process blocks concurrently. The keystream
/// for each block is generated independently through the following pipeline:
///
/// 1. **Counter Initialization**: $B = \text{Nonce} + \text{offset} + i$
/// 2. **Initial Whitening**: $B \leftarrow B \oplus K_0$
/// 3. **Round Operations**: For each round $r$ and key $K_r$ (from 1 to $N$):
/// * **Key Addition**: $B \leftarrow B \oplus K_r$
/// * **Nonlinear Mixing**: $B \leftarrow \text{Subcell}(B, r)$
/// * **Row Permutation**: $B \leftarrow \text{ShiftRows}(B, K_r)$
/// * **Column Diffusion**: $B \leftarrow \text{MixColumns}(B, K_r)$
///
/// # Parameters
/// - `grids`: A mutable slice of [`Grid`]s representing the plaintext or ciphertext.
/// - `nonce`: The initial counter [`Grid`] (IV).
/// - `round_keys`: A sequence of round keys derived from the master key.
/// - `counter_offset`: An optional offset for the block counter. Essential for stream processing
/// to prevent nonce reuse across consecutive data chunks. Defaults to `0` if `None`.