Skip to main content

noxtls_crypto/sym/encryption/
aria.rs

1// Copyright (c) 2019-2026, Argenox Technologies LLC
2// All rights reserved.
3//
4// SPDX-License-Identifier: GPL-2.0-only OR LicenseRef-Argenox-Commercial-License
5//
6// This file is part of the NoxTLS Library.
7//
8// This program is free software: you can redistribute it and/or modify
9// it under the terms of the GNU General Public License as published by the
10// Free Software Foundation; version 2 of the License.
11//
12// Alternatively, this file may be used under the terms of a commercial
13// license from Argenox Technologies LLC.
14//
15// See `noxtls/LICENSE` and `noxtls/LICENSE.md` in this repository for full details.
16// CONTACT: info@argenox.com
17
18use crate::internal_alloc::Vec;
19use noxtls_core::{Error, Result};
20
21const ARIA_S1: [u8; 256] = [
22    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
23    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
24    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
25    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
26    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
27    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
28    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
29    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
30    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
31    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
32    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
33    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
34    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
35    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
36    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
37    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
38];
39
40const ARIA_S2: [u8; 256] = [
41    0xe2, 0x4e, 0x54, 0xfc, 0x94, 0xc2, 0x4a, 0xcc, 0x62, 0x0d, 0x6a, 0x46, 0x3c, 0x4d, 0x8b, 0xd1,
42    0x5e, 0xfa, 0x64, 0xcb, 0xb4, 0x97, 0xbe, 0x2b, 0xbc, 0x77, 0x2e, 0x03, 0xd3, 0x19, 0x59, 0xc1,
43    0x1d, 0x06, 0x41, 0x6b, 0x55, 0xf0, 0x99, 0x69, 0xea, 0x9c, 0x18, 0xae, 0x63, 0xdf, 0xe7, 0xbb,
44    0x00, 0x73, 0x66, 0xfb, 0x96, 0x4c, 0x85, 0xe4, 0x3a, 0x09, 0x45, 0xaa, 0x0f, 0xee, 0x10, 0xeb,
45    0x2d, 0x7f, 0xf4, 0x29, 0xac, 0xcf, 0xad, 0x91, 0x8d, 0x78, 0xc8, 0x95, 0xf9, 0x2f, 0xce, 0xcd,
46    0x08, 0x7a, 0x88, 0x38, 0x5c, 0x83, 0x2a, 0x28, 0x47, 0xdb, 0xb8, 0xc7, 0x93, 0xa4, 0x12, 0x53,
47    0xff, 0x87, 0x0e, 0x31, 0x36, 0x21, 0x58, 0x48, 0x01, 0x8e, 0x37, 0x74, 0x32, 0xca, 0xe9, 0xb1,
48    0xb7, 0xab, 0x0c, 0xd7, 0xc4, 0x56, 0x42, 0x26, 0x07, 0x98, 0x60, 0xd9, 0xb6, 0xb9, 0x11, 0x40,
49    0xec, 0x20, 0x8c, 0xbd, 0xa0, 0xc9, 0x84, 0x04, 0x49, 0x23, 0xf1, 0x4f, 0x50, 0x1f, 0x13, 0xdc,
50    0xd8, 0xc0, 0x9e, 0x57, 0xe3, 0xc3, 0x7b, 0x65, 0x3b, 0x02, 0x8f, 0x3e, 0xe8, 0x25, 0x92, 0xe5,
51    0x15, 0xdd, 0xfd, 0x17, 0xa9, 0xbf, 0xd4, 0x9a, 0x7e, 0xc5, 0x39, 0x67, 0xfe, 0x76, 0x9d, 0x43,
52    0xa7, 0xe1, 0xd0, 0xf5, 0x68, 0xf2, 0x1b, 0x34, 0x70, 0x05, 0xa3, 0x8a, 0xd5, 0x79, 0x86, 0xa8,
53    0x30, 0xc6, 0x51, 0x4b, 0x1e, 0xa6, 0x27, 0xf6, 0x35, 0xd2, 0x6e, 0x24, 0x16, 0x82, 0x5f, 0xda,
54    0xe6, 0x75, 0xa2, 0xef, 0x2c, 0xb2, 0x1c, 0x9f, 0x5d, 0x6f, 0x80, 0x0a, 0x72, 0x44, 0x9b, 0x6c,
55    0x90, 0x0b, 0x5b, 0x33, 0x7d, 0x5a, 0x52, 0xf3, 0x61, 0xa1, 0xf7, 0xb0, 0xd6, 0x3f, 0x7c, 0x6d,
56    0xed, 0x14, 0xe0, 0xa5, 0x3d, 0x22, 0xb3, 0xf8, 0x89, 0xde, 0x71, 0x1a, 0xaf, 0xba, 0xb5, 0x81,
57];
58
59const C1: [u8; 16] = [
60    0x51, 0x7c, 0xc1, 0xb7, 0x27, 0x22, 0x0a, 0x94, 0xfe, 0x13, 0xab, 0xe8, 0xfa, 0x9a, 0x6e, 0xe0,
61];
62const C2: [u8; 16] = [
63    0x6d, 0xb1, 0x4a, 0xcc, 0x9e, 0x21, 0xc8, 0x20, 0xff, 0x28, 0xb1, 0xd5, 0xef, 0x5d, 0xe2, 0xb0,
64];
65const C3: [u8; 16] = [
66    0xdb, 0x92, 0x37, 0x1d, 0x21, 0x26, 0xe9, 0x70, 0x03, 0x24, 0x97, 0x75, 0x04, 0xe8, 0xc9, 0x0e,
67];
68
69/// Implements ARIA block cipher with key schedule and block operations.
70#[derive(Debug, Clone)]
71pub struct AriaCipher {
72    round_keys: [[u8; 16]; 17],
73    rounds: usize,
74}
75
76impl AriaCipher {
77    /// Constructs ARIA key schedule for 128/192/256-bit keys.
78    ///
79    /// # Arguments
80    /// * `key`: ARIA key bytes (16, 24, or 32 bytes).
81    ///
82    /// # Returns
83    /// Initialized `AriaCipher` with round keys.
84    pub fn noxtls_new(key: &[u8]) -> Result<Self> {
85        let (rounds, ck1, ck2, ck3) = match key.len() {
86            16 => (12, &C1, &C2, &C3),
87            24 => (14, &C2, &C3, &C1),
88            32 => (16, &C3, &C1, &C2),
89            _ => {
90                return Err(Error::InvalidLength(
91                    "aria key length must be 16, 24, or 32 bytes",
92                ));
93            }
94        };
95
96        let mut kl = [0_u8; 16];
97        kl.copy_from_slice(&key[..16]);
98        let mut kr = [0_u8; 16];
99        match key.len() {
100            16 => {}
101            24 => {
102                kr[..8].copy_from_slice(&key[16..24]);
103            }
104            32 => {
105                kr.copy_from_slice(&key[16..32]);
106            }
107            _ => unreachable!(),
108        }
109
110        let w0 = kl;
111        let mut w1 = fo(&w0, ck1);
112        xor_block_in_place(&mut w1, &kr);
113        let mut w2 = fe(&w1, ck2);
114        xor_block_in_place(&mut w2, &w0);
115        let mut w3 = fo(&w2, ck3);
116        xor_block_in_place(&mut w3, &w1);
117
118        let mut ek = [[0_u8; 16]; 17];
119        let mut rot = [0_u8; 16];
120
121        rotate_right_128(&w1, &mut rot, 19);
122        ek[0] = xor_block(&w0, &rot);
123        rotate_right_128(&w2, &mut rot, 19);
124        ek[1] = xor_block(&w1, &rot);
125        rotate_right_128(&w3, &mut rot, 19);
126        ek[2] = xor_block(&w2, &rot);
127        rotate_right_128(&w0, &mut rot, 19);
128        ek[3] = xor_block(&rot, &w3);
129
130        rotate_right_128(&w1, &mut rot, 31);
131        ek[4] = xor_block(&w0, &rot);
132        rotate_right_128(&w2, &mut rot, 31);
133        ek[5] = xor_block(&w1, &rot);
134        rotate_right_128(&w3, &mut rot, 31);
135        ek[6] = xor_block(&w2, &rot);
136        rotate_right_128(&w0, &mut rot, 31);
137        ek[7] = xor_block(&rot, &w3);
138
139        rotate_left_128(&w1, &mut rot, 61);
140        ek[8] = xor_block(&w0, &rot);
141        rotate_left_128(&w2, &mut rot, 61);
142        ek[9] = xor_block(&w1, &rot);
143        rotate_left_128(&w3, &mut rot, 61);
144        ek[10] = xor_block(&w2, &rot);
145        rotate_left_128(&w0, &mut rot, 61);
146        ek[11] = xor_block(&rot, &w3);
147
148        rotate_left_128(&w1, &mut rot, 31);
149        ek[12] = xor_block(&w0, &rot);
150        rotate_left_128(&w2, &mut rot, 31);
151        ek[13] = xor_block(&w1, &rot);
152        rotate_left_128(&w3, &mut rot, 31);
153        ek[14] = xor_block(&w2, &rot);
154        rotate_left_128(&w0, &mut rot, 31);
155        ek[15] = xor_block(&rot, &w3);
156
157        rotate_left_128(&w1, &mut rot, 19);
158        ek[16] = xor_block(&w0, &rot);
159
160        let mut enc = Self {
161            round_keys: [[0_u8; 16]; 17],
162            rounds,
163        };
164        enc.round_keys[..=rounds].copy_from_slice(&ek[..=rounds]);
165        Ok(enc)
166    }
167
168    /// Encrypts one 16-byte ARIA block in place.
169    ///
170    /// # Arguments
171    /// * `block`: Mutable 16-byte block to encrypt in place.
172    pub fn encrypt_block(&self, block: &mut [u8; 16]) -> Result<()> {
173        let mut state = *block;
174        for round in 1..self.rounds {
175            if (round & 1) != 0 {
176                state = fo(&state, &self.round_keys[round - 1]);
177            } else {
178                state = fe(&state, &self.round_keys[round - 1]);
179            }
180        }
181        xor_block_in_place(&mut state, &self.round_keys[self.rounds - 1]);
182        sl2(&mut state);
183        xor_block_in_place(&mut state, &self.round_keys[self.rounds]);
184        *block = state;
185        Ok(())
186    }
187
188    /// Decrypts one 16-byte ARIA block in place.
189    ///
190    /// # Arguments
191    /// * `block`: Mutable 16-byte block to decrypt in place.
192    pub fn decrypt_block(&self, block: &mut [u8; 16]) -> Result<()> {
193        let mut temp = self.round_keys;
194        let rounds = self.rounds;
195
196        let mut dec_keys = [[0_u8; 16]; 17];
197        dec_keys[0] = temp[rounds];
198        for i in 1..rounds {
199            dec_keys[i] = temp[rounds - i];
200            diffusion_layer(&mut dec_keys[i]);
201        }
202        dec_keys[rounds] = temp[0];
203
204        temp = dec_keys;
205        let mut state = *block;
206        for round in 1..rounds {
207            if (round & 1) != 0 {
208                state = fo(&state, &temp[round - 1]);
209            } else {
210                state = fe(&state, &temp[round - 1]);
211            }
212        }
213        xor_block_in_place(&mut state, &temp[rounds - 1]);
214        sl2(&mut state);
215        xor_block_in_place(&mut state, &temp[rounds]);
216        *block = state;
217        Ok(())
218    }
219}
220
221/// Encrypts ARIA-ECB over full blocks; input length must be multiple of 16.
222#[cfg(feature = "hazardous-legacy-crypto")]
223pub fn noxtls_aria_ecb_encrypt(cipher: &AriaCipher, input: &[u8]) -> Result<Vec<u8>> {
224    if input.len() % 16 != 0 {
225        return Err(Error::InvalidLength("aria ecb input must be block-aligned"));
226    }
227    let mut out = input.to_vec();
228    for chunk in out.chunks_exact_mut(16) {
229        let mut block = [0_u8; 16];
230        block.copy_from_slice(chunk);
231        cipher.encrypt_block(&mut block)?;
232        chunk.copy_from_slice(&block);
233    }
234    Ok(out)
235}
236
237/// Decrypts ARIA-ECB over full blocks; input length must be multiple of 16.
238#[cfg(feature = "hazardous-legacy-crypto")]
239pub fn noxtls_aria_ecb_decrypt(cipher: &AriaCipher, input: &[u8]) -> Result<Vec<u8>> {
240    if input.len() % 16 != 0 {
241        return Err(Error::InvalidLength("aria ecb input must be block-aligned"));
242    }
243    let mut out = input.to_vec();
244    for chunk in out.chunks_exact_mut(16) {
245        let mut block = [0_u8; 16];
246        block.copy_from_slice(chunk);
247        cipher.decrypt_block(&mut block)?;
248        chunk.copy_from_slice(&block);
249    }
250    Ok(out)
251}
252
253/// Encrypts ARIA-CBC with a 16-byte IV and block-aligned plaintext.
254pub fn noxtls_aria_cbc_encrypt(
255    cipher: &AriaCipher,
256    iv: &[u8; 16],
257    plaintext: &[u8],
258) -> Result<Vec<u8>> {
259    if plaintext.len() % 16 != 0 {
260        return Err(Error::InvalidLength("aria cbc input must be block-aligned"));
261    }
262    let mut out = plaintext.to_vec();
263    let mut prev = *iv;
264    for chunk in out.chunks_exact_mut(16) {
265        for (i, byte) in chunk.iter_mut().enumerate() {
266            *byte ^= prev[i];
267        }
268        let mut block = [0_u8; 16];
269        block.copy_from_slice(chunk);
270        cipher.encrypt_block(&mut block)?;
271        chunk.copy_from_slice(&block);
272        prev = block;
273    }
274    Ok(out)
275}
276
277/// Decrypts ARIA-CBC with a 16-byte IV and block-aligned ciphertext.
278pub fn noxtls_aria_cbc_decrypt(
279    cipher: &AriaCipher,
280    iv: &[u8; 16],
281    ciphertext: &[u8],
282) -> Result<Vec<u8>> {
283    if ciphertext.len() % 16 != 0 {
284        return Err(Error::InvalidLength("aria cbc input must be block-aligned"));
285    }
286    let mut out = ciphertext.to_vec();
287    let mut prev = *iv;
288    for chunk in out.chunks_exact_mut(16) {
289        let mut cur = [0_u8; 16];
290        cur.copy_from_slice(chunk);
291        let mut block = cur;
292        cipher.decrypt_block(&mut block)?;
293        for i in 0..16 {
294            block[i] ^= prev[i];
295        }
296        chunk.copy_from_slice(&block);
297        prev = cur;
298    }
299    Ok(out)
300}
301
302/// Applies ARIA-CTR transformation using a 16-byte initial counter block.
303#[must_use]
304pub fn noxtls_aria_ctr_apply(
305    cipher: &AriaCipher,
306    nonce_counter: &[u8; 16],
307    input: &[u8],
308) -> Vec<u8> {
309    noxtls_aria_ctr_encrypt(cipher, nonce_counter, input)
310}
311
312/// Encrypts bytes with ARIA-CTR using a 16-byte initial counter block.
313#[must_use]
314pub fn noxtls_aria_ctr_encrypt(
315    cipher: &AriaCipher,
316    nonce_counter: &[u8; 16],
317    plaintext: &[u8],
318) -> Vec<u8> {
319    aria_ctr_process(cipher, nonce_counter, plaintext)
320}
321
322/// Decrypts bytes with ARIA-CTR using a 16-byte initial counter block.
323#[must_use]
324pub fn noxtls_aria_ctr_decrypt(
325    cipher: &AriaCipher,
326    nonce_counter: &[u8; 16],
327    ciphertext: &[u8],
328) -> Vec<u8> {
329    aria_ctr_process(cipher, nonce_counter, ciphertext)
330}
331
332/// Applies CTR keystream XOR (same operation for encrypt/decrypt).
333///
334/// # Arguments
335///
336/// * `cipher` — `&AriaCipher`.
337/// * `nonce_counter` — `&[u8; 16]`.
338/// * `input` — `&[u8]`.
339///
340/// # Returns
341///
342/// `Vec<u8>` produced by `aria_ctr_process` (see implementation).
343///
344/// # Panics
345///
346/// This function does not panic unless otherwise noted.
347fn aria_ctr_process(cipher: &AriaCipher, nonce_counter: &[u8; 16], input: &[u8]) -> Vec<u8> {
348    let mut out = vec![0_u8; input.len()];
349    let mut counter = *nonce_counter;
350    let mut offset = 0;
351    while offset < input.len() {
352        let mut stream = counter;
353        cipher
354            .encrypt_block(&mut stream)
355            .expect("aria block encryption should not fail");
356        let chunk_len = (input.len() - offset).min(16);
357        for i in 0..chunk_len {
358            out[offset + i] = input[offset + i] ^ stream[i];
359        }
360        increment_be(&mut counter);
361        offset += chunk_len;
362    }
363    out
364}
365
366/// Applies ARIA-CFB-128 transformation with a 16-byte IV.
367#[must_use]
368pub fn noxtls_aria_cfb_apply(cipher: &AriaCipher, iv: &[u8; 16], input: &[u8]) -> Vec<u8> {
369    noxtls_aria_cfb_encrypt(cipher, iv, input)
370}
371
372/// Encrypts bytes with ARIA-CFB-128 using a 16-byte IV/register.
373#[must_use]
374pub fn noxtls_aria_cfb_encrypt(cipher: &AriaCipher, iv: &[u8; 16], plaintext: &[u8]) -> Vec<u8> {
375    aria_cfb_process(cipher, iv, plaintext, true)
376}
377
378/// Decrypts bytes with ARIA-CFB-128 using a 16-byte IV/register.
379#[must_use]
380pub fn noxtls_aria_cfb_decrypt(cipher: &AriaCipher, iv: &[u8; 16], ciphertext: &[u8]) -> Vec<u8> {
381    aria_cfb_process(cipher, iv, ciphertext, false)
382}
383
384/// Applies CFB keystream XOR with direction-specific register updates.
385///
386/// # Arguments
387///
388/// * `cipher` — `&AriaCipher`.
389/// * `iv` — `&[u8; 16]`.
390/// * `input` — `&[u8]`.
391/// * `encrypt` — `bool`.
392///
393/// # Returns
394///
395/// `Vec<u8>` produced by `aria_cfb_process` (see implementation).
396///
397/// # Panics
398///
399/// This function does not panic unless otherwise noted.
400fn aria_cfb_process(cipher: &AriaCipher, iv: &[u8; 16], input: &[u8], encrypt: bool) -> Vec<u8> {
401    let mut out = vec![0_u8; input.len()];
402    let mut reg = *iv;
403    let mut offset = 0;
404    while offset < input.len() {
405        let mut stream = reg;
406        cipher
407            .encrypt_block(&mut stream)
408            .expect("aria block encryption should not fail");
409        let chunk_len = (input.len() - offset).min(16);
410        for i in 0..chunk_len {
411            out[offset + i] = input[offset + i] ^ stream[i];
412        }
413        if encrypt {
414            shift_register_append(&mut reg, &out[offset..offset + chunk_len]);
415        } else {
416            shift_register_append(&mut reg, &input[offset..offset + chunk_len]);
417        }
418        offset += chunk_len;
419    }
420    out
421}
422
423/// Applies ARIA-OFB transformation with a 16-byte IV.
424#[must_use]
425pub fn noxtls_aria_ofb_apply(cipher: &AriaCipher, iv: &[u8; 16], input: &[u8]) -> Vec<u8> {
426    noxtls_aria_ofb_encrypt(cipher, iv, input)
427}
428
429/// Encrypts bytes with ARIA-OFB using a 16-byte IV.
430#[must_use]
431pub fn noxtls_aria_ofb_encrypt(cipher: &AriaCipher, iv: &[u8; 16], plaintext: &[u8]) -> Vec<u8> {
432    aria_ofb_process(cipher, iv, plaintext)
433}
434
435/// Decrypts bytes with ARIA-OFB using a 16-byte IV.
436#[must_use]
437pub fn noxtls_aria_ofb_decrypt(cipher: &AriaCipher, iv: &[u8; 16], ciphertext: &[u8]) -> Vec<u8> {
438    aria_ofb_process(cipher, iv, ciphertext)
439}
440
441/// Applies OFB keystream XOR (same operation for encrypt/decrypt).
442///
443/// # Arguments
444///
445/// * `cipher` — `&AriaCipher`.
446/// * `iv` — `&[u8; 16]`.
447/// * `input` — `&[u8]`.
448///
449/// # Returns
450///
451/// `Vec<u8>` produced by `aria_ofb_process` (see implementation).
452///
453/// # Panics
454///
455/// This function does not panic unless otherwise noted.
456fn aria_ofb_process(cipher: &AriaCipher, iv: &[u8; 16], input: &[u8]) -> Vec<u8> {
457    let mut out = vec![0_u8; input.len()];
458    let mut stream = *iv;
459    let mut offset = 0;
460    while offset < input.len() {
461        cipher
462            .encrypt_block(&mut stream)
463            .expect("aria block encryption should not fail");
464        let chunk_len = (input.len() - offset).min(16);
465        for i in 0..chunk_len {
466            out[offset + i] = input[offset + i] ^ stream[i];
467        }
468        offset += chunk_len;
469    }
470    out
471}
472
473/// Increments a big-endian 128-bit counter in place.
474///
475/// # Arguments
476///
477/// * `counter` — `&mut [u8; 16]`.
478///
479/// # Returns
480///
481/// `()` when there is no return data.
482///
483/// # Panics
484///
485/// This function does not panic unless otherwise noted.
486fn increment_be(counter: &mut [u8; 16]) {
487    for b in counter.iter_mut().rev() {
488        *b = b.wrapping_add(1);
489        if *b != 0 {
490            break;
491        }
492    }
493}
494
495/// Applies ARIA FO layer.
496///
497/// # Arguments
498///
499/// * `input` — `&[u8; 16]`.
500/// * `rk` — `&[u8; 16]`.
501///
502/// # Returns
503///
504/// `[u8` produced by `fo` (see implementation).
505///
506/// # Panics
507///
508/// This function does not panic unless otherwise noted.
509fn fo(input: &[u8; 16], rk: &[u8; 16]) -> [u8; 16] {
510    let mut out = *input;
511    xor_block_in_place(&mut out, rk);
512    sl1(&mut out);
513    diffusion_layer(&mut out);
514    out
515}
516
517/// Applies ARIA FE layer.
518///
519/// # Arguments
520///
521/// * `input` — `&[u8; 16]`.
522/// * `rk` — `&[u8; 16]`.
523///
524/// # Returns
525///
526/// `[u8` produced by `fe` (see implementation).
527///
528/// # Panics
529///
530/// This function does not panic unless otherwise noted.
531fn fe(input: &[u8; 16], rk: &[u8; 16]) -> [u8; 16] {
532    let mut out = *input;
533    xor_block_in_place(&mut out, rk);
534    sl2(&mut out);
535    diffusion_layer(&mut out);
536    out
537}
538
539/// Applies ARIA substitution layer type 1.
540///
541/// # Arguments
542///
543/// * `state` — `&mut [u8; 16]`.
544///
545/// # Returns
546///
547/// `()` when there is no return data.
548///
549/// # Panics
550///
551/// This function does not panic unless otherwise noted.
552fn sl1(state: &mut [u8; 16]) {
553    let (inv_s1, inv_s2) = inverse_sboxes();
554    state[0] = ARIA_S1[state[0] as usize];
555    state[1] = ARIA_S2[state[1] as usize];
556    state[2] = inv_s1[state[2] as usize];
557    state[3] = inv_s2[state[3] as usize];
558    state[4] = ARIA_S1[state[4] as usize];
559    state[5] = ARIA_S2[state[5] as usize];
560    state[6] = inv_s1[state[6] as usize];
561    state[7] = inv_s2[state[7] as usize];
562    state[8] = ARIA_S1[state[8] as usize];
563    state[9] = ARIA_S2[state[9] as usize];
564    state[10] = inv_s1[state[10] as usize];
565    state[11] = inv_s2[state[11] as usize];
566    state[12] = ARIA_S1[state[12] as usize];
567    state[13] = ARIA_S2[state[13] as usize];
568    state[14] = inv_s1[state[14] as usize];
569    state[15] = inv_s2[state[15] as usize];
570}
571
572/// Applies ARIA substitution layer type 2.
573///
574/// # Arguments
575///
576/// * `state` — `&mut [u8; 16]`.
577///
578/// # Returns
579///
580/// `()` when there is no return data.
581///
582/// # Panics
583///
584/// This function does not panic unless otherwise noted.
585fn sl2(state: &mut [u8; 16]) {
586    let (inv_s1, inv_s2) = inverse_sboxes();
587    state[0] = inv_s1[state[0] as usize];
588    state[1] = inv_s2[state[1] as usize];
589    state[2] = ARIA_S1[state[2] as usize];
590    state[3] = ARIA_S2[state[3] as usize];
591    state[4] = inv_s1[state[4] as usize];
592    state[5] = inv_s2[state[5] as usize];
593    state[6] = ARIA_S1[state[6] as usize];
594    state[7] = ARIA_S2[state[7] as usize];
595    state[8] = inv_s1[state[8] as usize];
596    state[9] = inv_s2[state[9] as usize];
597    state[10] = ARIA_S1[state[10] as usize];
598    state[11] = ARIA_S2[state[11] as usize];
599    state[12] = inv_s1[state[12] as usize];
600    state[13] = inv_s2[state[13] as usize];
601    state[14] = ARIA_S1[state[14] as usize];
602    state[15] = ARIA_S2[state[15] as usize];
603}
604
605/// Applies ARIA diffusion layer matrix multiplication.
606///
607/// # Arguments
608///
609/// * `state` — `&mut [u8; 16]`.
610///
611/// # Returns
612///
613/// `()` when there is no return data.
614///
615/// # Panics
616///
617/// This function does not panic unless otherwise noted.
618fn diffusion_layer(state: &mut [u8; 16]) {
619    let mut temp = [0_u8; 16];
620    temp[0] = state[3] ^ state[4] ^ state[6] ^ state[8] ^ state[9] ^ state[13] ^ state[14];
621    temp[1] = state[2] ^ state[5] ^ state[7] ^ state[8] ^ state[9] ^ state[12] ^ state[15];
622    temp[2] = state[1] ^ state[4] ^ state[6] ^ state[10] ^ state[11] ^ state[12] ^ state[15];
623    temp[3] = state[0] ^ state[5] ^ state[7] ^ state[10] ^ state[11] ^ state[13] ^ state[14];
624    temp[4] = state[0] ^ state[2] ^ state[5] ^ state[8] ^ state[11] ^ state[14] ^ state[15];
625    temp[5] = state[1] ^ state[3] ^ state[4] ^ state[9] ^ state[10] ^ state[14] ^ state[15];
626    temp[6] = state[0] ^ state[2] ^ state[7] ^ state[9] ^ state[10] ^ state[12] ^ state[13];
627    temp[7] = state[1] ^ state[3] ^ state[6] ^ state[8] ^ state[11] ^ state[12] ^ state[13];
628    temp[8] = state[0] ^ state[1] ^ state[4] ^ state[7] ^ state[10] ^ state[13] ^ state[15];
629    temp[9] = state[0] ^ state[1] ^ state[5] ^ state[6] ^ state[11] ^ state[12] ^ state[14];
630    temp[10] = state[2] ^ state[3] ^ state[5] ^ state[6] ^ state[8] ^ state[13] ^ state[15];
631    temp[11] = state[2] ^ state[3] ^ state[4] ^ state[7] ^ state[9] ^ state[12] ^ state[14];
632    temp[12] = state[1] ^ state[2] ^ state[6] ^ state[7] ^ state[9] ^ state[11] ^ state[12];
633    temp[13] = state[0] ^ state[3] ^ state[6] ^ state[7] ^ state[8] ^ state[10] ^ state[13];
634    temp[14] = state[0] ^ state[3] ^ state[4] ^ state[5] ^ state[9] ^ state[11] ^ state[14];
635    temp[15] = state[1] ^ state[2] ^ state[4] ^ state[5] ^ state[8] ^ state[10] ^ state[15];
636    *state = temp;
637}
638
639/// Builds inverse S-box tables from forward S-box constants.
640///
641/// # Arguments
642///
643/// * *(none)* — This function takes no parameters.
644///
645/// # Returns
646///
647/// `([u8` produced by `inverse_sboxes` (see implementation).
648///
649/// # Panics
650///
651/// This function does not panic unless otherwise noted.
652fn inverse_sboxes() -> ([u8; 256], [u8; 256]) {
653    let mut inv_s1 = [0_u8; 256];
654    let mut inv_s2 = [0_u8; 256];
655    for (idx, val) in ARIA_S1.iter().enumerate() {
656        inv_s1[*val as usize] = idx as u8;
657    }
658    for (idx, val) in ARIA_S2.iter().enumerate() {
659        inv_s2[*val as usize] = idx as u8;
660    }
661    (inv_s1, inv_s2)
662}
663
664/// XORs two 128-bit blocks.
665///
666/// # Arguments
667///
668/// * `a` — `&[u8; 16]`.
669/// * `b` — `&[u8; 16]`.
670///
671/// # Returns
672///
673/// `[u8` produced by `xor_block` (see implementation).
674///
675/// # Panics
676///
677/// This function does not panic unless otherwise noted.
678fn xor_block(a: &[u8; 16], b: &[u8; 16]) -> [u8; 16] {
679    let mut out = [0_u8; 16];
680    for i in 0..16 {
681        out[i] = a[i] ^ b[i];
682    }
683    out
684}
685
686/// XORs `rhs` into `lhs` block in place.
687///
688/// # Arguments
689///
690/// * `lhs` — `&mut [u8; 16]`.
691/// * `rhs` — `&[u8; 16]`.
692///
693/// # Returns
694///
695/// `()` when there is no return data.
696///
697/// # Panics
698///
699/// This function does not panic unless otherwise noted.
700fn xor_block_in_place(lhs: &mut [u8; 16], rhs: &[u8; 16]) {
701    for i in 0..16 {
702        lhs[i] ^= rhs[i];
703    }
704}
705
706/// Shifts CFB register left by segment length and appends segment bytes.
707///
708/// # Arguments
709///
710/// * `reg` — `&mut [u8; 16]`.
711/// * `segment` — `&[u8]`.
712///
713/// # Returns
714///
715/// `()` when there is no return data.
716///
717/// # Panics
718///
719/// This function does not panic unless otherwise noted.
720fn shift_register_append(reg: &mut [u8; 16], segment: &[u8]) {
721    debug_assert!(segment.len() <= 16);
722    if segment.len() == 16 {
723        reg.copy_from_slice(segment);
724        return;
725    }
726    let keep = 16 - segment.len();
727    reg.copy_within(segment.len().., 0);
728    reg[keep..].copy_from_slice(segment);
729}
730
731/// Rotates a 128-bit block right by `bits`.
732///
733/// # Arguments
734///
735/// * `input` — `&[u8; 16]`.
736/// * `out` — `&mut [u8; 16]`.
737/// * `bits` — `usize`.
738///
739/// # Returns
740///
741/// `()` when there is no return data.
742///
743/// # Panics
744///
745/// This function does not panic unless otherwise noted.
746fn rotate_right_128(input: &[u8; 16], out: &mut [u8; 16], bits: usize) {
747    let b = bits & 127;
748    if b == 0 {
749        *out = *input;
750        return;
751    }
752    let hi = u64::from_be_bytes(input[..8].try_into().expect("slice is 8 bytes"));
753    let lo = u64::from_be_bytes(input[8..].try_into().expect("slice is 8 bytes"));
754    let (new_hi, new_lo) = if b < 64 {
755        ((hi >> b) | (lo << (64 - b)), (lo >> b) | (hi << (64 - b)))
756    } else if b == 64 {
757        (lo, hi)
758    } else {
759        let s = b - 64;
760        ((lo >> s) | (hi << (64 - s)), (hi >> s) | (lo << (64 - s)))
761    };
762    out[..8].copy_from_slice(&new_hi.to_be_bytes());
763    out[8..].copy_from_slice(&new_lo.to_be_bytes());
764}
765
766/// Rotates a 128-bit block left by `bits`.
767///
768/// # Arguments
769///
770/// * `input` — `&[u8; 16]`.
771/// * `out` — `&mut [u8; 16]`.
772/// * `bits` — `usize`.
773///
774/// # Returns
775///
776/// `()` when there is no return data.
777///
778/// # Panics
779///
780/// This function does not panic unless otherwise noted.
781fn rotate_left_128(input: &[u8; 16], out: &mut [u8; 16], bits: usize) {
782    rotate_right_128(input, out, 128 - (bits & 127));
783}