Skip to main content

crypto/aes/
aes.rs

1/// Pure-Rust AES block cipher (128-bit and 256-bit keys).
2///
3/// The software implementation is **constant-time**: it uses no lookup tables
4/// and no secret-dependent branches, so it does not leak key or data bytes
5/// through cache or timing side channels (see [`super::aes_ct`]). Hardware
6/// paths (AES-NI / ARMv8) are used when available and are used in preference
7/// to this fallback.
8#[cfg(test)]
9use super::ghash::gf128_mul;
10
11// ── AES constants ─────────────────────────────────────────────────────────────
12
13pub const GCM_MAX_LEN: u64 = (u32::MAX as u64 - 1) * 16;
14
15#[cfg(test)]
16#[rustfmt::skip]
17pub(crate) const SBOX: [u8; 256] = [
18    0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
19    0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
20    0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
21    0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
22    0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
23    0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
24    0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
25    0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
26    0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
27    0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
28    0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
29    0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
30    0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
31    0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
32    0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
33    0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
34];
35
36#[cfg(test)]
37#[rustfmt::skip]
38pub(crate) const SBOX_INV: [u8; 256] = [
39    0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
40    0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
41    0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
42    0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
43    0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
44    0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
45    0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
46    0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
47    0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
48    0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
49    0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
50    0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
51    0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
52    0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
53    0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
54    0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
55];
56
57/// Round constants for AES key expansion (RCON[1..10]).
58pub(crate) const RCON: [u8; 11] = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
59
60// ── AES key schedule ───────────────────────────────────────────────────────────
61
62/// AES expanded key: `N` round keys x 16 bytes.
63/// N = 11 for AES-128 and 15 for AES-256
64#[derive(Clone)]
65#[cfg_attr(feature = "zeroize", derive(zeroize::Zeroize, zeroize::ZeroizeOnDrop))]
66pub(crate) enum RoundKeys<const N: usize> {
67    #[cfg(target_arch = "x86_64")]
68    /// The platform supports x86 AES-NI instructions
69    X86_64([core::arch::x86_64::__m128i; N]),
70
71    #[cfg(target_arch = "aarch64")]
72    /// The platform supports ARMv8 AES instructions
73    Armv8([core::arch::aarch64::uint8x16_t; N]),
74
75    /// The platform doesn't support AES hardware acceleration
76    Software([[u8; 16]; N]),
77}
78
79pub(crate) type RoundKeysSoftware<const N: usize> = [[u8; 16]; N];
80
81#[inline(always)]
82fn rot_word(w: [u8; 4]) -> [u8; 4] {
83    [w[1], w[2], w[3], w[0]]
84}
85
86/// AES `SubWord`: apply the S-box to each byte of a word in constant time.
87#[inline(always)]
88fn sub_word(w: [u8; 4]) -> [u8; 4] {
89    super::aes_ct::sub_word(u32::from_le_bytes(w)).to_le_bytes()
90}
91
92/// Expand a key into AES round keys (FIPS 197 §5.2).
93///
94/// - `N = 11` -> AES-128 (Nk=4, Nr=10, 44 words -> 11 round keys)
95/// - `N = 15` -> AES-256 (Nk=8, Nr=14, 60 words -> 15 round keys)
96///
97/// The schedule is computed with a constant-time S-box (no table lookups).
98pub fn expand_key<const N: usize>(key: &[u8]) -> RoundKeysSoftware<N> {
99    const {
100        assert!(N == 11 || N == 15);
101    }
102    let nk = key.len() / 4;
103    let words = N * 4;
104
105    // Max 60 words (AES-256). Use a fixed-size buffer for both key sizes.
106    let mut w = [[0u8; 4]; 60];
107    for i in 0..nk {
108        w[i] = [key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]];
109    }
110
111    for i in nk..words {
112        let mut temp = w[i - 1];
113        if i % nk == 0 {
114            temp = sub_word(rot_word(temp));
115            temp[0] ^= RCON[i / nk];
116        } else if N == 15 && i % nk == 4 {
117            // AES-256 only: SubWord every 4 words within the Nk=8 group
118            temp = sub_word(temp);
119        }
120        w[i] = [
121            w[i - nk][0] ^ temp[0],
122            w[i - nk][1] ^ temp[1],
123            w[i - nk][2] ^ temp[2],
124            w[i - nk][3] ^ temp[3],
125        ];
126    }
127
128    let mut rk = [[0u8; 16]; N];
129    for i in 0..N {
130        for j in 0..4 {
131            rk[i][4 * j..4 * j + 4].copy_from_slice(&w[4 * i + j]);
132        }
133    }
134    rk
135}
136
137// ── AES block cipher (encrypt / decrypt) ─────────────────────────────────────
138
139/// Encrypt one 16-byte block.
140///
141/// `N = 11` for AES-128 (10 rounds), `N = 15` for AES-256 (14 rounds).
142///
143/// This is the constant-time software path; it performs no data-dependent
144/// memory accesses or branches.
145pub fn encrypt_block<const N: usize>(round_keys: &RoundKeysSoftware<N>, block: &[u8; 16]) -> [u8; 16] {
146    const {
147        assert!(N == 11 || N == 15);
148    }
149    let sched = super::aes_ct::keysched(round_keys);
150    super::aes_ct::encrypt_block_sched(&sched, block)
151}
152
153/// Decrypt one 16-byte block.
154///
155/// `N = 11` for AES-128 (10 rounds), `N = 15` for AES-256 (14 rounds).
156///
157/// This is the constant-time software path; it performs no data-dependent
158/// memory accesses or branches.
159pub fn decrypt_block<const N: usize>(round_keys: &RoundKeysSoftware<N>, block: &[u8; 16]) -> [u8; 16] {
160    const {
161        assert!(N == 11 || N == 15);
162    }
163    let sched = super::aes_ct::keysched(round_keys);
164    super::aes_ct::decrypt_block_sched(&sched, block)
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170
171    // ── AES-256 block cipher (FIPS 197 Appendix B + C) ────────────────────────
172
173    /// NIST FIPS 197 Appendix B – AES-128 vectors (re-confirmed in AES-256 test)
174    /// These come from FIPS 197 Appendix C.3 (AES-256).
175    #[test]
176    fn fips197_aes256_encrypt() {
177        // FIPS 197 Appendix C.3
178        let key: [u8; 32] =
179            hex::decode_array::<32>(b"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap();
180        let pt: [u8; 16] = hex::decode_array::<16>(b"00112233445566778899aabbccddeeff").unwrap();
181        let ct_expected: [u8; 16] = hex::decode_array::<16>(b"8ea2b7ca516745bfeafc49904b496089").unwrap();
182
183        let rk = expand_key::<15>(&key);
184        let ct = encrypt_block(&rk, &pt);
185        assert_eq!(ct, ct_expected);
186    }
187
188    #[test]
189    fn fips197_aes256_decrypt() {
190        let key: [u8; 32] =
191            hex::decode_array::<32>(b"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f").unwrap();
192        let ct: [u8; 16] = hex::decode_array::<16>(b"8ea2b7ca516745bfeafc49904b496089").unwrap();
193        let pt_expected: [u8; 16] = hex::decode_array::<16>(b"00112233445566778899aabbccddeeff").unwrap();
194
195        let rk = expand_key::<15>(&key);
196        let pt = decrypt_block(&rk, &ct);
197        assert_eq!(pt, pt_expected);
198    }
199
200    /// NIST SP 800-38A ECB-AES256 vectors (F.1.5 / F.1.6).
201    #[test]
202    fn nist_sp800_38a_aes256_ecb() {
203        let key: [u8; 32] =
204            hex::decode_array::<32>(b"603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4").unwrap();
205
206        let blocks: &[([u8; 16], [u8; 16])] = &[
207            (
208                hex::decode_array::<16>(b"6bc1bee22e409f96e93d7e117393172a").unwrap(),
209                hex::decode_array::<16>(b"f3eed1bdb5d2a03c064b5a7e3db181f8").unwrap(),
210            ),
211            (
212                hex::decode_array::<16>(b"ae2d8a571e03ac9c9eb76fac45af8e51").unwrap(),
213                hex::decode_array::<16>(b"591ccb10d410ed26dc5ba74a31362870").unwrap(),
214            ),
215            (
216                hex::decode_array::<16>(b"30c81c46a35ce411e5fbc1191a0a52ef").unwrap(),
217                hex::decode_array::<16>(b"b6ed21b99ca6f4f9f153e7b1beafed1d").unwrap(),
218            ),
219            (
220                hex::decode_array::<16>(b"f69f2445df4f9b17ad2b417be66c3710").unwrap(),
221                hex::decode_array::<16>(b"23304b7a39f9f3ff067d8d8f9e24ecc7").unwrap(),
222            ),
223        ];
224
225        let rk = expand_key::<15>(&key);
226        for (pt, ct) in blocks {
227            assert_eq!(encrypt_block(&rk, pt), *ct);
228            assert_eq!(decrypt_block(&rk, ct), *pt);
229        }
230    }
231
232    /// NIST Known Answer Test (KAT) – a few AES-256 single-block KATs.
233    #[test]
234    fn aes256_kat_vectors() {
235        // key, plaintext, ciphertext
236        let vectors: &[([u8; 32], [u8; 16], [u8; 16])] = &[
237            // All-zero key and plaintext
238            (
239                [0u8; 32],
240                [0u8; 16],
241                hex::decode_array::<16>(b"dc95c078a2408989ad48a21492842087").unwrap(),
242            ),
243            // Key = 0x01..0x20, PT = 0
244            (
245                hex::decode_array::<32>(b"0101010101010101010101010101010101010101010101010101010101010101").unwrap(),
246                [0u8; 16],
247                hex::decode_array::<16>(b"7298caa565031eadc6ce23d23ea66378").unwrap(),
248            ),
249            // Key = 0xff..0xff
250            (
251                [0xff; 32],
252                [0u8; 16],
253                hex::decode_array::<16>(b"4bf85f1b5d54adbc307b0a048389adcb").unwrap(),
254            ),
255        ];
256
257        for (key, pt, ct_expected) in vectors {
258            let rk = expand_key::<15>(key);
259            let ct = encrypt_block(&rk, pt);
260            assert_eq!(ct, *ct_expected, "key={}", hex::encode(key));
261            let pt2 = decrypt_block(&rk, &ct);
262            assert_eq!(pt2, *pt, "round-trip failed");
263        }
264    }
265
266    #[test]
267    fn encrypt_decrypt_roundtrip_random() {
268        let key: [u8; 32] =
269            hex::decode_array::<32>(b"deadbeefcafebabedeadbeefcafebabe0011223344556677deadbeefcafebabe").unwrap();
270        let rk = expand_key::<15>(&key);
271        for seed in 0u8..=255 {
272            let pt = [seed; 16];
273            let ct = encrypt_block(&rk, &pt);
274            let pt2 = decrypt_block(&rk, &ct);
275            assert_eq!(pt2, pt);
276        }
277    }
278
279    // ── GF(2^128) multiplication ───────────────────────────────────────────────
280
281    #[test]
282    fn gf128_mul_zero() {
283        let h = [
284            0x66, 0xe9, 0x4b, 0xd4, 0xef, 0x8a, 0x2c, 0x3b, 0x88, 0x4c, 0xfa, 0x59, 0xca, 0x34, 0x2b, 0x2e,
285        ];
286        let zero = [0u8; 16];
287        assert_eq!(gf128_mul(&zero, &h), zero);
288        assert_eq!(gf128_mul(&h, &zero), zero);
289    }
290
291    #[test]
292    fn gf128_mul_commutativity() {
293        let a: [u8; 16] = hex::decode_array::<16>(b"66e94bd4ef8a2c3b884cfa59ca342b2e").unwrap();
294        let b: [u8; 16] = hex::decode_array::<16>(b"feedfacedeadbeeffeedfacedeadbeef").unwrap();
295        assert_eq!(gf128_mul(&a, &b), gf128_mul(&b, &a));
296    }
297
298    // H and X from GCM Test Case 2 (NIST SP 800-38D Appendix B).
299    #[test]
300    fn gf128_mul_nist_tv2() {
301        // H = AES_K(0) for K = all-zeros 128-bit key -> irrelevant for 256-bit here,
302        // but we test the raw GF multiplication with known values from NIST test vectors.
303        // From TC2: H = 66e94bd4ef8a2c3b884cfa59ca342b2e
304        //           X (first GHASH input) = feedfacedeadbeeffeedfacedeadbeef
305        // Expected product from the NIST spec reference implementation.
306        let h: [u8; 16] = hex::decode_array::<16>(b"66e94bd4ef8a2c3b884cfa59ca342b2e").unwrap();
307        let x: [u8; 16] = hex::decode_array::<16>(b"feedfacedeadbeeffeedfacedeadbeef").unwrap();
308        // Computed offline with a reference implementation.
309        let expected: [u8; 16] = hex::decode_array::<16>(b"88eddca9968dec8b9c952d6ae0290a82").unwrap();
310        assert_eq!(gf128_mul(&x, &h), expected);
311    }
312}