Skip to main content

sponge_hash_aes256/
utilities.rs

1// SPDX-License-Identifier: 0BSD
2// SpongeHash-AES256
3// Copyright (C) 2025-2026 by LoRd_MuldeR <mulder2@gmx.de>
4
5use aes::{
6    cipher::{BlockCipherEncrypt, Key, KeyInit},
7    Aes256Enc,
8};
9use core::{
10    mem::MaybeUninit,
11    ops::{Index, IndexMut, RangeTo},
12    ptr,
13};
14use wide::u8x16;
15use zeroize::zeroize_flat_type;
16
17pub const BLOCK_SIZE: usize = 16usize;
18pub const ZERO: u8x16 = u8x16::ZERO;
19
20// ---------------------------------------------------------------------------
21// Block type
22// ---------------------------------------------------------------------------
23
24/// Represents an aligned 128-Bit block
25#[derive(Clone, Debug)]
26#[repr(align(16))]
27pub struct BlockType(u8x16);
28
29impl BlockType {
30    /// Create a new block that is initialized entirely from the given `INIT_VALUE`
31    #[inline(always)]
32    pub const fn new<const INIT_VALUE: u8>() -> Self {
33        Self(u8x16::new([INIT_VALUE; BLOCK_SIZE]))
34    }
35
36    /// Create a new block that is initialized from the given array
37    #[cfg(test)]
38    pub const fn from_array(value: [u8; BLOCK_SIZE]) -> Self {
39        Self(u8x16::new(value))
40    }
41
42    /// Create a new block that is initialized to "zero" bytes
43    #[inline(always)]
44    pub const fn zero() -> Self {
45        unsafe { Self(MaybeUninit::zeroed().assume_init()) }
46    }
47
48    /// Create a new block that is *not* initialized to any particular state
49    #[allow(invalid_value)]
50    #[allow(clippy::uninit_assumed_init)]
51    #[inline(always)]
52    pub const fn uninit() -> Self {
53        unsafe { Self(MaybeUninit::uninit().assume_init()) }
54    }
55
56    /// Computes the bit-wise XOR of `other` and *self*, stores the result "in-place" in *self*
57    #[inline(always)]
58    pub fn xor_with(&mut self, other: &Self) {
59        self.0 ^= other.0;
60    }
61
62    /// Computes the bit-wise XOR of `raw_data` and *self*, stores the result "in-place" in *self*
63    #[inline(always)]
64    pub fn xor_with_u8_ptr(&mut self, raw_data: *const u8) {
65        unsafe {
66            self.0 ^= u8x16::new(*raw_data.cast::<[u8; BLOCK_SIZE]>());
67        }
68    }
69
70    /// Get a `&[u8; BLOCK_SIZE]` reference to the contained data
71    #[inline(always)]
72    fn as_array(&self) -> &[u8; BLOCK_SIZE] {
73        self.0.as_array()
74    }
75
76    /// Get a `&mut [u8; BLOCK_SIZE]` reference to the contained data
77    #[inline(always)]
78    fn as_mut_array(&mut self) -> &mut [u8; BLOCK_SIZE] {
79        self.0.as_mut_array()
80    }
81
82    /// Get a "raw" `*const u8` pointer to the contained data
83    #[inline(always)]
84    fn as_ptr(&self) -> *const [u8; BLOCK_SIZE] {
85        self.0.as_array().as_ptr() as *const [u8; BLOCK_SIZE]
86    }
87}
88
89impl Index<usize> for BlockType {
90    type Output = u8;
91
92    #[inline(always)]
93    fn index(&self, index: usize) -> &Self::Output {
94        &self.0.as_array()[index]
95    }
96}
97
98impl IndexMut<usize> for BlockType {
99    #[inline(always)]
100    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
101        &mut self.0.as_mut_array()[index]
102    }
103}
104
105impl Index<RangeTo<usize>> for BlockType {
106    type Output = [u8];
107
108    #[inline(always)]
109    fn index(&self, range: RangeTo<usize>) -> &Self::Output {
110        &self.0.as_array()[range]
111    }
112}
113
114impl PartialEq for BlockType {
115    #[inline(always)]
116    fn eq(&self, other: &Self) -> bool {
117        self.0 ^ other.0 == ZERO
118    }
119}
120
121impl Drop for BlockType {
122    #[inline(always)]
123    fn drop(&mut self) {
124        unsafe {
125            zeroize_flat_type(self);
126        }
127    }
128}
129
130// ---------------------------------------------------------------------------
131// Key type
132// ---------------------------------------------------------------------------
133
134/// Represents an aligned 256-Bit key
135#[repr(align(32))]
136pub struct KeyType(Key<Aes256Enc>);
137
138impl KeyType {
139    /// Concatenate the two 128-bit blocks `key0` and `key1` to from a full 256-bit key
140    #[allow(invalid_value)]
141    #[allow(clippy::uninit_assumed_init)]
142    #[inline(always)]
143    pub const fn uninit() -> Self {
144        unsafe { MaybeUninit::uninit().assume_init() }
145    }
146
147    /// Concatenate the two 128-bit blocks `key0` and `key1` to from a full 256-bit key
148    #[inline(always)]
149    pub fn concat(&mut self, key0: &BlockType, key1: &BlockType) -> &Key<Aes256Enc> {
150        unsafe {
151            let write_ptr = self.0.as_mut_ptr() as *mut [u8; BLOCK_SIZE];
152            ptr::copy_nonoverlapping(key0.as_ptr(), write_ptr, 1usize);
153            ptr::copy_nonoverlapping(key1.as_ptr(), write_ptr.add(1usize), 1usize);
154        }
155        &self.0
156    }
157}
158
159impl Drop for KeyType {
160    #[inline(always)]
161    fn drop(&mut self) {
162        unsafe {
163            zeroize_flat_type(self);
164        }
165    }
166}
167
168// ---------------------------------------------------------------------------
169// AES-256 Utility
170// ---------------------------------------------------------------------------
171
172/// Handles encryption with the AES-256 block cipher
173pub struct Aes256Crypto {
174    key: KeyType,
175}
176
177impl Aes256Crypto {
178    /// Encrypes the 128-bit block `src` with AES-256 and stores the result in `dst`.
179    ///
180    /// The 128 key bits from `key0` and the 128 key bits from `key1` are concatenated to form a full 256-bit key.
181    #[inline]
182    pub fn encrypt(&mut self, dst: &mut BlockType, src: &BlockType, key0: &BlockType, key1: &BlockType) {
183        let cipher = Aes256Enc::new(self.key.concat(key0, key1));
184        cipher.encrypt_block_b2b(src.as_array().into(), dst.as_mut_array().into());
185    }
186}
187
188impl Default for Aes256Crypto {
189    /// Creates a new `Aes256Processor` instance
190    #[inline]
191    fn default() -> Self {
192        Self { key: KeyType::uninit() }
193    }
194}
195
196// ---------------------------------------------------------------------------
197// Functions
198// ---------------------------------------------------------------------------
199
200/// Determines the length, in bytes, of the range specified by two "raw" adjacent pointers
201#[inline(always)]
202pub fn length(from: *const u8, to: *const u8) -> usize {
203    debug_assert!(to >= from);
204    unsafe { to.offset_from(from) as usize }
205}
206
207/// Returns the version of the library as a string
208pub const fn version() -> &'static str {
209    static PKG_VERSION: &str = env!("CARGO_PKG_VERSION");
210    PKG_VERSION
211}
212
213// ---------------------------------------------------------------------------
214// Tests
215// ---------------------------------------------------------------------------
216
217#[cfg(test)]
218mod tests {
219    mod aes256_encrypt {
220        use super::super::*;
221        use hex_literal::hex;
222
223        const KEY_0: BlockType = BlockType::from_array(hex!("603deb1015ca71be2b73aef0857d7781"));
224        const KEY_1: BlockType = BlockType::from_array(hex!("1f352c073b6108d72d9810a30914dff4"));
225
226        fn do_aes256_ecb(input: &BlockType, expected: &BlockType, key0: &BlockType, key1: &BlockType) {
227            let mut output = BlockType::zero();
228            Aes256Crypto::default().encrypt(&mut output, input, key0, key1);
229            assert_eq!(&output, expected);
230        }
231
232        #[test]
233        fn test_aes256_ecb_1a() {
234            do_aes256_ecb(
235                &BlockType::from_array(hex!("6bc1bee22e409f96e93d7e117393172a")),
236                &BlockType::from_array(hex!("f3eed1bdb5d2a03c064b5a7e3db181f8")),
237                &KEY_0,
238                &KEY_1,
239            );
240        }
241
242        #[test]
243        fn test_aes256_ecb_1b() {
244            do_aes256_ecb(
245                &BlockType::from_array(hex!("6bc1bee22e409f96e93d7e117393172a")),
246                &BlockType::from_array(hex!("5ba1a80938bf65904c5a406f5651b88c")),
247                &KEY_1,
248                &KEY_0,
249            );
250        }
251
252        #[test]
253        fn test_aes256_ecb_2a() {
254            do_aes256_ecb(
255                &BlockType::from_array(hex!("ae2d8a571e03ac9c9eb76fac45af8e51")),
256                &BlockType::from_array(hex!("591ccb10d410ed26dc5ba74a31362870")),
257                &KEY_0,
258                &KEY_1,
259            );
260        }
261
262        #[test]
263        fn test_aes256_ecb_2b() {
264            do_aes256_ecb(
265                &BlockType::from_array(hex!("ae2d8a571e03ac9c9eb76fac45af8e51")),
266                &BlockType::from_array(hex!("1f38958fe69e4c58d7b0e908000be9b9")),
267                &KEY_1,
268                &KEY_0,
269            );
270        }
271
272        #[test]
273        fn test_aes256_ecb_3a() {
274            do_aes256_ecb(
275                &BlockType::from_array(hex!("30c81c46a35ce411e5fbc1191a0a52ef")),
276                &BlockType::from_array(hex!("b6ed21b99ca6f4f9f153e7b1beafed1d")),
277                &KEY_0,
278                &KEY_1,
279            );
280        }
281
282        #[test]
283        fn test_aes256_ecb_3b() {
284            do_aes256_ecb(
285                &BlockType::from_array(hex!("30c81c46a35ce411e5fbc1191a0a52ef")),
286                &BlockType::from_array(hex!("139a83bda68fe6438220eaa3aa17e849")),
287                &KEY_1,
288                &KEY_0,
289            );
290        }
291
292        #[test]
293        fn test_aes256_ecb_4a() {
294            do_aes256_ecb(
295                &BlockType::from_array(hex!("f69f2445df4f9b17ad2b417be66c3710")),
296                &BlockType::from_array(hex!("23304b7a39f9f3ff067d8d8f9e24ecc7")),
297                &KEY_0,
298                &KEY_1,
299            );
300        }
301
302        #[test]
303        fn test_aes256_ecb_4b() {
304            do_aes256_ecb(
305                &BlockType::from_array(hex!("f69f2445df4f9b17ad2b417be66c3710")),
306                &BlockType::from_array(hex!("5b3fbfb893c88a7252f14f5d9a4a0054")),
307                &KEY_1,
308                &KEY_0,
309            );
310        }
311    }
312
313    mod xor_arrays {
314        use super::super::*;
315        use hex_literal::hex;
316
317        fn do_xor_arrays(input0: &BlockType, input1: &BlockType) {
318            let mut output_xor = input0.clone();
319            let mut output_ptr = input0.clone();
320            let mut output_ref = input0.clone();
321
322            output_xor.xor_with(input1);
323            output_ptr.xor_with_u8_ptr(input1.as_array().as_ptr());
324
325            for (dst, src) in output_ref.as_mut_array().iter_mut().zip(input1.as_array().iter()) {
326                *dst ^= src;
327            }
328
329            assert_eq!(&output_xor, &output_ref);
330            assert_eq!(&output_ptr, &output_ref);
331        }
332
333        #[test]
334        fn test_xor_arrays_1() {
335            do_xor_arrays(&BlockType::from_array(hex!("75863721fe83cf3d6f0500df428126ae")), &BlockType::from_array(hex!("cc39d4653cce685b8de3398eccfe9c48")));
336        }
337
338        #[test]
339        fn test_xor_arrays_2() {
340            do_xor_arrays(&BlockType::from_array(hex!("2381643e0214c832064a0e8fd074055d")), &BlockType::from_array(hex!("ab290a75923b190ed775841e4cca9e25")));
341        }
342
343        #[test]
344        fn test_xor_arrays_3() {
345            do_xor_arrays(&BlockType::from_array(hex!("62f828dce94781e2d31d9ffa786df6e4")), &BlockType::from_array(hex!("ca6bb37d92d3f8a997d561d9e9d7030e")));
346        }
347
348        #[test]
349        fn test_xor_arrays_4() {
350            do_xor_arrays(&BlockType::from_array(hex!("710180b32b5a982ee21d8e76d287e509")), &BlockType::from_array(hex!("389b742402576214410c0633722c593a")));
351        }
352    }
353
354    mod concat_keys {
355        use super::super::*;
356        use hex_literal::hex;
357
358        fn do_concat_keys(input0: &BlockType, input1: &BlockType) {
359            let mut buffer = KeyType::uninit();
360            let key_data = buffer.concat(input0, input1).as_slice();
361            assert_eq!(input0, &BlockType::from_array(key_data[..BLOCK_SIZE].try_into().unwrap()));
362            assert_eq!(input1, &BlockType::from_array(key_data[BLOCK_SIZE..].try_into().unwrap()));
363        }
364
365        #[test]
366        fn test_concat_keys_1a() {
367            do_concat_keys(&BlockType::from_array(hex!("000102030405060708090A0B0C0D0E0F")), &BlockType::from_array(hex!("F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF")));
368        }
369
370        #[test]
371        fn test_concat_keys_1b() {
372            do_concat_keys(&BlockType::from_array(hex!("F0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFF")), &BlockType::from_array(hex!("000102030405060708090A0B0C0D0E0F")));
373        }
374
375        #[test]
376        fn test_concat_keys_2a() {
377            do_concat_keys(&BlockType::from_array(hex!("00102030405060708090A0B0C0D0E0F0")), &BlockType::from_array(hex!("0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFFF")));
378        }
379
380        #[test]
381        fn test_concat_keys_2b() {
382            do_concat_keys(&BlockType::from_array(hex!("0F1F2F3F4F5F6F7F8F9FAFBFCFDFEFFF")), &BlockType::from_array(hex!("00102030405060708090A0B0C0D0E0F0")));
383        }
384    }
385
386    mod index {
387        use super::super::*;
388
389        #[test]
390        fn test_block_index() {
391            let mut block = BlockType::new::<0u8>();
392            block[0usize] = 1u8;
393            assert_eq!(block[0usize], 1u8);
394        }
395
396        #[test]
397        fn test_block_range() {
398            let block = BlockType::new::<0u8>();
399            let range = &block[..4usize];
400            assert_eq!(range, &[0u8, 0u8, 0u8, 0u8]);
401        }
402    }
403}