1use crate::primitives::PrimitivesError;
8
9#[rustfmt::skip]
11const SBOX: [u8; 256] = [
12 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
13 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
14 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
15 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
16 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
17 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
18 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
19 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
20 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
21 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
22 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
23 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
24 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
25 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
26 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
27 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
28];
29
30#[rustfmt::skip]
32const INV_SBOX: [u8; 256] = [
33 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb,
34 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb,
35 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e,
36 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25,
37 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92,
38 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84,
39 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06,
40 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b,
41 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73,
42 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e,
43 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b,
44 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4,
45 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f,
46 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef,
47 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61,
48 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d,
49];
50
51#[rustfmt::skip]
53const RCON: [u32; 11] = [
54 0x00000000,
55 0x01000000,
56 0x02000000,
57 0x04000000,
58 0x08000000,
59 0x10000000,
60 0x20000000,
61 0x40000000,
62 0x80000000,
63 0x1b000000,
64 0x36000000,
65];
66
67pub struct AesKey {
69 pub round_keys: Vec<u32>,
71 pub rounds: usize,
73}
74
75impl AesKey {
76 pub fn new(key: &[u8]) -> Result<Self, PrimitivesError> {
78 let rounds = match key.len() {
79 16 => 10,
80 32 => 14,
81 _ => {
82 return Err(PrimitivesError::InvalidLength(format!(
83 "AES key must be 16 or 32 bytes, got {}",
84 key.len()
85 )))
86 }
87 };
88 let round_keys = aes_key_expansion(key)?;
89 Ok(AesKey { round_keys, rounds })
90 }
91
92 pub fn encrypt_block(&self, block: &[u8; 16]) -> [u8; 16] {
94 aes_encrypt_block(block, &self.round_keys)
95 }
96
97 pub fn decrypt_block(&self, block: &[u8; 16]) -> [u8; 16] {
99 aes_decrypt_block(block, &self.round_keys)
100 }
101}
102
103#[inline]
105fn xtime(a: u8) -> u8 {
106 let shifted = (a as u16) << 1;
107 let mask = if a & 0x80 != 0 { 0x1b } else { 0x00 };
108 (shifted as u8) ^ mask
109}
110
111#[inline]
113fn gmul(a: u8, b: u8) -> u8 {
114 let mut result = 0u8;
115 let mut aa = a;
116 let mut bb = b;
117 for _ in 0..8 {
118 if bb & 1 != 0 {
119 result ^= aa;
120 }
121 aa = xtime(aa);
122 bb >>= 1;
123 }
124 result
125}
126
127#[inline]
129fn sub_word(w: u32) -> u32 {
130 let b0 = SBOX[((w >> 24) & 0xff) as usize] as u32;
131 let b1 = SBOX[((w >> 16) & 0xff) as usize] as u32;
132 let b2 = SBOX[((w >> 8) & 0xff) as usize] as u32;
133 let b3 = SBOX[(w & 0xff) as usize] as u32;
134 (b0 << 24) | (b1 << 16) | (b2 << 8) | b3
135}
136
137#[inline]
139fn rot_word(w: u32) -> u32 {
140 w.rotate_left(8)
141}
142
143pub fn aes_key_expansion(key: &[u8]) -> Result<Vec<u32>, PrimitivesError> {
146 let nk = key.len() / 4; let nr = match nk {
148 4 => 10,
149 8 => 14,
150 _ => {
151 return Err(PrimitivesError::InvalidLength(format!(
152 "invalid AES key length: {} bytes (expected 16 or 32)",
153 key.len()
154 )))
155 }
156 };
157 let total_words = 4 * (nr + 1);
158
159 let mut w = Vec::with_capacity(total_words);
160
161 for i in 0..nk {
163 let word = ((key[4 * i] as u32) << 24)
164 | ((key[4 * i + 1] as u32) << 16)
165 | ((key[4 * i + 2] as u32) << 8)
166 | (key[4 * i + 3] as u32);
167 w.push(word);
168 }
169
170 for i in nk..total_words {
172 let mut temp = w[i - 1];
173 if i % nk == 0 {
174 temp = sub_word(rot_word(temp)) ^ RCON[i / nk];
175 } else if nk > 6 && (i % nk) == 4 {
176 temp = sub_word(temp);
177 }
178 w.push(w[i - nk] ^ temp);
179 }
180
181 Ok(w)
182}
183
184pub fn aes_encrypt_block(block: &[u8; 16], round_keys: &[u32]) -> [u8; 16] {
187 let nr = (round_keys.len() / 4) - 1; let mut state = [[0u8; 4]; 4];
191 for c in 0..4 {
192 for r in 0..4 {
193 state[c][r] = block[c * 4 + r];
194 }
195 }
196
197 add_round_key(&mut state, round_keys, 0);
199
200 for round in 1..nr {
202 sub_bytes(&mut state);
203 shift_rows(&mut state);
204 mix_columns(&mut state);
205 add_round_key(&mut state, round_keys, round);
206 }
207
208 sub_bytes(&mut state);
210 shift_rows(&mut state);
211 add_round_key(&mut state, round_keys, nr);
212
213 let mut output = [0u8; 16];
215 for c in 0..4 {
216 for r in 0..4 {
217 output[c * 4 + r] = state[c][r];
218 }
219 }
220 output
221}
222
223pub fn aes_decrypt_block(block: &[u8; 16], round_keys: &[u32]) -> [u8; 16] {
226 let nr = (round_keys.len() / 4) - 1;
227
228 let mut state = [[0u8; 4]; 4];
230 for c in 0..4 {
231 for r in 0..4 {
232 state[c][r] = block[c * 4 + r];
233 }
234 }
235
236 add_round_key(&mut state, round_keys, nr);
238
239 for round in (1..nr).rev() {
241 inv_shift_rows(&mut state);
242 inv_sub_bytes(&mut state);
243 add_round_key(&mut state, round_keys, round);
244 inv_mix_columns(&mut state);
245 }
246
247 inv_shift_rows(&mut state);
249 inv_sub_bytes(&mut state);
250 add_round_key(&mut state, round_keys, 0);
251
252 let mut output = [0u8; 16];
254 for c in 0..4 {
255 for r in 0..4 {
256 output[c * 4 + r] = state[c][r];
257 }
258 }
259 output
260}
261
262#[inline]
266fn add_round_key(state: &mut [[u8; 4]; 4], round_keys: &[u32], round: usize) {
267 for c in 0..4 {
268 let rk = round_keys[round * 4 + c];
269 state[c][0] ^= ((rk >> 24) & 0xff) as u8;
270 state[c][1] ^= ((rk >> 16) & 0xff) as u8;
271 state[c][2] ^= ((rk >> 8) & 0xff) as u8;
272 state[c][3] ^= (rk & 0xff) as u8;
273 }
274}
275
276#[inline]
278fn sub_bytes(state: &mut [[u8; 4]; 4]) {
279 for c in 0..4 {
280 for r in 0..4 {
281 state[c][r] = SBOX[state[c][r] as usize];
282 }
283 }
284}
285
286#[inline]
288fn inv_sub_bytes(state: &mut [[u8; 4]; 4]) {
289 for c in 0..4 {
290 for r in 0..4 {
291 state[c][r] = INV_SBOX[state[c][r] as usize];
292 }
293 }
294}
295
296#[inline]
300fn shift_rows(state: &mut [[u8; 4]; 4]) {
301 let tmp = state[0][1];
303 state[0][1] = state[1][1];
304 state[1][1] = state[2][1];
305 state[2][1] = state[3][1];
306 state[3][1] = tmp;
307
308 let tmp0 = state[0][2];
310 let tmp1 = state[1][2];
311 state[0][2] = state[2][2];
312 state[1][2] = state[3][2];
313 state[2][2] = tmp0;
314 state[3][2] = tmp1;
315
316 let tmp = state[3][3];
318 state[3][3] = state[2][3];
319 state[2][3] = state[1][3];
320 state[1][3] = state[0][3];
321 state[0][3] = tmp;
322}
323
324#[inline]
326fn inv_shift_rows(state: &mut [[u8; 4]; 4]) {
327 let tmp = state[3][1];
329 state[3][1] = state[2][1];
330 state[2][1] = state[1][1];
331 state[1][1] = state[0][1];
332 state[0][1] = tmp;
333
334 let tmp0 = state[0][2];
336 let tmp1 = state[1][2];
337 state[0][2] = state[2][2];
338 state[1][2] = state[3][2];
339 state[2][2] = tmp0;
340 state[3][2] = tmp1;
341
342 let tmp = state[0][3];
344 state[0][3] = state[1][3];
345 state[1][3] = state[2][3];
346 state[2][3] = state[3][3];
347 state[3][3] = tmp;
348}
349
350#[inline]
352#[allow(clippy::needless_range_loop)]
353fn mix_columns(state: &mut [[u8; 4]; 4]) {
354 for c in 0..4 {
355 let s0 = state[c][0];
356 let s1 = state[c][1];
357 let s2 = state[c][2];
358 let s3 = state[c][3];
359
360 state[c][0] = xtime(s0) ^ (xtime(s1) ^ s1) ^ s2 ^ s3;
361 state[c][1] = s0 ^ xtime(s1) ^ (xtime(s2) ^ s2) ^ s3;
362 state[c][2] = s0 ^ s1 ^ xtime(s2) ^ (xtime(s3) ^ s3);
363 state[c][3] = (xtime(s0) ^ s0) ^ s1 ^ s2 ^ xtime(s3);
364 }
365}
366
367#[inline]
369#[allow(clippy::needless_range_loop)]
370fn inv_mix_columns(state: &mut [[u8; 4]; 4]) {
371 for c in 0..4 {
372 let s0 = state[c][0];
373 let s1 = state[c][1];
374 let s2 = state[c][2];
375 let s3 = state[c][3];
376
377 state[c][0] = gmul(s0, 0x0e) ^ gmul(s1, 0x0b) ^ gmul(s2, 0x0d) ^ gmul(s3, 0x09);
378 state[c][1] = gmul(s0, 0x09) ^ gmul(s1, 0x0e) ^ gmul(s2, 0x0b) ^ gmul(s3, 0x0d);
379 state[c][2] = gmul(s0, 0x0d) ^ gmul(s1, 0x09) ^ gmul(s2, 0x0e) ^ gmul(s3, 0x0b);
380 state[c][3] = gmul(s0, 0x0b) ^ gmul(s1, 0x0d) ^ gmul(s2, 0x09) ^ gmul(s3, 0x0e);
381 }
382}
383
384#[cfg(test)]
385mod tests {
386 use super::*;
387
388 fn hex_to_bytes(hex: &str) -> Vec<u8> {
389 (0..hex.len())
390 .step_by(2)
391 .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).unwrap())
392 .collect()
393 }
394
395 fn bytes_to_hex(bytes: &[u8]) -> String {
396 bytes.iter().map(|b| format!("{:02x}", b)).collect()
397 }
398
399 #[test]
400 fn test_aes128_nist_fips197_appendix_b() {
401 let key = hex_to_bytes("2b7e151628aed2a6abf7158809cf4f3c");
403 let plaintext = hex_to_bytes("3243f6a8885a308d313198a2e0370734");
404 let expected = hex_to_bytes("3925841d02dc09fbdc118597196a0b32");
405
406 let round_keys = aes_key_expansion(&key).unwrap();
407 let block: [u8; 16] = plaintext.try_into().unwrap();
408 let result = aes_encrypt_block(&block, &round_keys);
409
410 assert_eq!(
411 bytes_to_hex(&result),
412 bytes_to_hex(&expected),
413 "AES-128 NIST FIPS 197 Appendix B failed"
414 );
415 }
416
417 #[test]
418 fn test_aes256_nist_fips197() {
419 let key = hex_to_bytes("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4");
421 let plaintext = hex_to_bytes("6bc1bee22e409f96e93d7e117393172a");
422 let expected = hex_to_bytes("f3eed1bdb5d2a03c064b5a7e3db181f8");
423
424 let round_keys = aes_key_expansion(&key).unwrap();
425 let block: [u8; 16] = plaintext.try_into().unwrap();
426 let result = aes_encrypt_block(&block, &round_keys);
427
428 assert_eq!(
429 bytes_to_hex(&result),
430 bytes_to_hex(&expected),
431 "AES-256 NIST test vector failed"
432 );
433 }
434
435 #[test]
436 fn test_aes128_encrypt_decrypt_roundtrip() {
437 let key = hex_to_bytes("2b7e151628aed2a6abf7158809cf4f3c");
438 let plaintext = hex_to_bytes("3243f6a8885a308d313198a2e0370734");
439 let round_keys = aes_key_expansion(&key).unwrap();
440
441 let block: [u8; 16] = plaintext.clone().try_into().unwrap();
442 let encrypted = aes_encrypt_block(&block, &round_keys);
443 let decrypted = aes_decrypt_block(&encrypted, &round_keys);
444
445 assert_eq!(
446 &decrypted[..],
447 &plaintext[..],
448 "AES-128 encrypt+decrypt round-trip failed"
449 );
450 }
451
452 #[test]
453 fn test_aes256_encrypt_decrypt_roundtrip() {
454 let key = hex_to_bytes("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4");
455 let plaintext = hex_to_bytes("6bc1bee22e409f96e93d7e117393172a");
456 let round_keys = aes_key_expansion(&key).unwrap();
457
458 let block: [u8; 16] = plaintext.clone().try_into().unwrap();
459 let encrypted = aes_encrypt_block(&block, &round_keys);
460 let decrypted = aes_decrypt_block(&encrypted, &round_keys);
461
462 assert_eq!(
463 &decrypted[..],
464 &plaintext[..],
465 "AES-256 encrypt+decrypt round-trip failed"
466 );
467 }
468
469 #[test]
470 fn test_aes128_key_expansion_length() {
471 let key = hex_to_bytes("2b7e151628aed2a6abf7158809cf4f3c");
472 let round_keys = aes_key_expansion(&key).unwrap();
473 assert_eq!(
475 round_keys.len(),
476 44,
477 "AES-128 should produce 44 round key words"
478 );
479 }
480
481 #[test]
482 fn test_aes256_key_expansion_length() {
483 let key = hex_to_bytes("603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4");
484 let round_keys = aes_key_expansion(&key).unwrap();
485 assert_eq!(
487 round_keys.len(),
488 60,
489 "AES-256 should produce 60 round key words"
490 );
491 }
492
493 #[test]
494 fn test_aes_key_struct() {
495 let key_bytes = hex_to_bytes("2b7e151628aed2a6abf7158809cf4f3c");
496 let aes_key = AesKey::new(&key_bytes).unwrap();
497 assert_eq!(aes_key.rounds, 10);
498
499 let plaintext: [u8; 16] = hex_to_bytes("3243f6a8885a308d313198a2e0370734")
500 .try_into()
501 .unwrap();
502 let encrypted = aes_key.encrypt_block(&plaintext);
503 let decrypted = aes_key.decrypt_block(&encrypted);
504 assert_eq!(decrypted, plaintext);
505 }
506
507 #[test]
508 fn test_aes_key_invalid_length() {
509 let result = AesKey::new(&[0u8; 24]);
510 assert!(result.is_err());
511 }
512}