Debian Codegraph @

debian/missing-sources/aes/src/armv8/expand.rs

raw
1 //! AES key expansion support.
2
3 use core::{arch::aarch64::*, mem, slice};
4
5 // Stable "polyfills" for unstable core::arch::aarch64 intrinsics
6 // TODO(tarcieri): remove when these intrinsics have been stabilized
7 use super::intrinsics::{vaeseq_u8, vaesimcq_u8};
8
9 /// There are 4 AES words in a block.
10 const BLOCK_WORDS: usize = 4;
11
12 /// The AES (nee Rijndael) notion of a word is always 32-bits, or 4-bytes.
13 const WORD_SIZE: usize = 4;
14
15 /// AES round constants.
16 const ROUND_CONSTS: [u32; 10] = [0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
17
18 /// AES key expansion.
19 #[target_feature(enable = "aes")]
20 pub unsafe fn expand_key<const L: usize, const N: usize>(key: &[u8; L]) -> [uint8x16_t; N] {
21 assert!((L == 16 && N == 11) || (L == 24 && N == 13) || (L == 32 && N == 15));
22
23 let mut expanded_keys: [uint8x16_t; N] = mem::zeroed();
24
25 // Sanity check, as this is required in order for the following line to be sound.
26 const _: () = assert!(mem::align_of::<uint8x16_t>() >= mem::align_of::<u32>());
27 let keys_ptr: *mut u32 = expanded_keys.as_mut_ptr().cast();
28 let columns = slice::from_raw_parts_mut(keys_ptr, N * BLOCK_WORDS);
29
30 for (i, chunk) in key.chunks_exact(WORD_SIZE).enumerate() {
31 columns[i] = u32::from_ne_bytes(chunk.try_into().unwrap());
32 }
33
34 // From "The Rijndael Block Cipher" Section 4.1:
35 // > The number of columns of the Cipher Key is denoted by `Nk` and is
36 // > equal to the key length divided by 32 [bits].
37 let nk = L / WORD_SIZE;
38
39 for i in nk..(N * BLOCK_WORDS) {
40 let mut word = columns[i - 1];
41
42 if i % nk == 0 {
43 word = sub_word(word).rotate_right(8) ^ ROUND_CONSTS[i / nk - 1];
44 } else if nk > 6 && i % nk == 4 {
45 word = sub_word(word);
46 }
47
48 columns[i] = columns[i - nk] ^ word;
49 }
50
51 expanded_keys
52 }
53
54 /// Compute inverse expanded keys (for decryption).
55 ///
56 /// This is the reverse of the encryption keys, with the Inverse Mix Columns
57 /// operation applied to all but the first and last expanded key.
58 #[target_feature(enable = "aes")]
59 pub(super) unsafe fn inv_expanded_keys<const N: usize>(expanded_keys: &mut [uint8x16_t; N]) {
60 assert!(N == 11 || N == 13 || N == 15);
61
62 for ek in expanded_keys.iter_mut().take(N - 1).skip(1) {
63 *ek = vaesimcq_u8(*ek);
64 }
65
66 expanded_keys.reverse();
67 }
68
69 /// Sub bytes for a single AES word: used for key expansion.
70 #[inline]
71 #[target_feature(enable = "aes")]
72 unsafe fn sub_word(input: u32) -> u32 {
73 let input = vreinterpretq_u8_u32(vdupq_n_u32(input));
74
75 // AES single round encryption (with a "round" key of all zeros)
76 let sub_input = vaeseq_u8(input, vdupq_n_u8(0));
77
78 vgetq_lane_u32(vreinterpretq_u32_u8(sub_input), 0)
79 }