interplane.Get Omega
Read in your language

aienux

Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.

Brought by drakestapleton

branch main Branches Tags History

aienux / crates / aienos-crypto / src / aes.rs

346 lines · 12428 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Pure-Rust, allocation-free AES-256 block cipher implementation conforming to FIPS 197.
17//!
18//! Designed for bare-metal `#![no_std]` without external dependencies.
19//!
20//! # Constant-time design
21//!
22//! The S-box is computed, not looked up: each byte is inverted in GF(2^8)
23//! (as `x^254`) and then passed through the FIPS 197 affine transform. All
24//! arithmetic is shifts, masks and XORs with a fixed number of steps, so no
25//! memory address and no branch depends on key or data bytes. The same S-box
26//! routine serves encryption (`SubBytes`) and key expansion (`SubWord`).
27//! Bytes are processed 16 at a time packed in a `u128` ("SIMD within a
28//! register"), which keeps the cost reasonable without a lookup table.
29//!
30//! This is slower than a table-driven AES. Hardware AES instructions
31//! (ARMv8 FEAT_AES: `AESE`/`AESMC`) are constant-time and much faster; they
32//! are a possible future speedup and are **not** implemented here.
33
34/// AES-256 expanded round keys (15 rounds, 4 words per round = 60 words = 240 bytes).
35#[derive(Clone)]
36pub struct Aes256Key {
37 round_keys: [u32; 60],
38}
39
40impl core::fmt::Debug for Aes256Key {
41 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
42 write!(f, "Aes256Key([REDACTED])")
43 }
44}
45
46impl Drop for Aes256Key {
47 fn drop(&mut self) {
48 for word in &mut self.round_keys {
49 unsafe { core::ptr::write_volatile(word, 0) };
50 }
51 core::sync::atomic::compiler_fence(core::sync::atomic::Ordering::SeqCst);
52 }
53}
54
55/// Round constants.
56const RCON: [u32; 10] = [
57 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000,
58 0x1b000000, 0x36000000,
59];
60
61/// `m` repeated in every byte lane of a `u128`.
62const fn lanes(m: u8) -> u128 {
63 (m as u128) * 0x0101_0101_0101_0101_0101_0101_0101_0101
64}
65
66const LSB: u128 = lanes(0x01);
67const LOW7: u128 = lanes(0x7f);
68
69/// Turn a lane value of 0 or 1 into 0x00 or 0xff, per lane, without branches.
70///
71/// `(bits << 8) - bits` equals `bits * 0xff` lane by lane: every lane's
72/// product fits in its own byte, so no carry or borrow crosses lanes, and the
73/// identity holds modulo 2^128 even when the top lane's shift falls off.
74#[inline(always)]
75fn lane_mask(bits: u128) -> u128 {
76 (bits << 8).wrapping_sub(bits)
77}
78
79/// Multiply every byte lane by `x` in GF(2^8) (FIPS 197 `xtime`), branch-free.
80#[inline(always)]
81fn xtime_lanes(a: u128) -> u128 {
82 let hi = (a >> 7) & LSB; // 0 or 1 per lane: did the top bit fall out?
83 // hi * 0x1b per lane, written as shifts so lanes stay independent.
84 let reduce = hi ^ (hi << 1) ^ (hi << 3) ^ (hi << 4);
85 ((a & LOW7) << 1) ^ reduce
86}
87
88/// Lane-wise GF(2^8) multiply `a * b` modulo x^8 + x^4 + x^3 + x + 1.
89///
90/// Always runs exactly 8 steps; each bit of `b` selects via a mask, not a branch.
91#[inline(always)]
92fn gf_mul_lanes(mut a: u128, b: u128) -> u128 {
93 let mut acc = 0u128;
94 let mut i = 0;
95 while i < 8 {
96 acc ^= a & lane_mask((b >> i) & LSB);
97 a = xtime_lanes(a);
98 i += 1;
99 }
100 acc
101}
102
103/// Lane-wise rotate-left of each byte by `k` (1..=7).
104#[inline(always)]
105fn rotl_lanes(x: u128, k: u32) -> u128 {
106 let hi = lanes(0xffu8 << k);
107 let lo = lanes(0xffu8 >> (8 - k));
108 ((x << k) & hi) | ((x >> (8 - k)) & lo)
109}
110
111/// Constant-time AES S-box applied to all 16 byte lanes of `x` at once.
112///
113/// S(b) = Affine(b^254), where b^254 is the multiplicative inverse of b in
114/// GF(2^8) (and 0 maps to 0). The exponent is reached with a fixed addition
115/// chain of 11 multiplications.
116#[inline(never)]
117fn sub_bytes_ct(x: u128) -> u128 {
118 let x2 = gf_mul_lanes(x, x);
119 let x3 = gf_mul_lanes(x2, x);
120 let x6 = gf_mul_lanes(x3, x3);
121 let x12 = gf_mul_lanes(x6, x6);
122 let x15 = gf_mul_lanes(x12, x3);
123 let x30 = gf_mul_lanes(x15, x15);
124 let x60 = gf_mul_lanes(x30, x30);
125 let x120 = gf_mul_lanes(x60, x60);
126 let x240 = gf_mul_lanes(x120, x120);
127 let x252 = gf_mul_lanes(x240, x12);
128 let inv = gf_mul_lanes(x252, x2);
129
130 // FIPS 197 affine transform: b ^ rotl1 ^ rotl2 ^ rotl3 ^ rotl4 ^ 0x63.
131 inv ^ rotl_lanes(inv, 1)
132 ^ rotl_lanes(inv, 2)
133 ^ rotl_lanes(inv, 3)
134 ^ rotl_lanes(inv, 4)
135 ^ lanes(0x63)
136}
137
138/// Constant-time S-box of a single byte (used by tests and for clarity).
139#[cfg(test)]
140fn sbox_ct(b: u8) -> u8 {
141 sub_bytes_ct(b as u128) as u8
142}
143
144#[inline(always)]
145fn sub_word(w: u32) -> u32 {
146 sub_bytes_ct(w as u128) as u32
147}
148
149#[inline(always)]
150fn rot_word(w: u32) -> u32 {
151 w.rotate_left(8)
152}
153
154#[inline(always)]
155fn xtime(x: u8) -> u8 {
156 // Branch-free: 0x1b where the top bit was set, 0 otherwise.
157 (x << 1) ^ (0x1bu8 & 0u8.wrapping_sub(x >> 7))
158}
159
160impl Aes256Key {
161 /// Expand a 32-byte key into 15 round keys per FIPS 197.
162 ///
163 /// The schedule is built directly inside the returned value, so no
164 /// separate stack copy of the round keys is left behind.
165 pub fn new(key: &[u8; 32]) -> Self {
166 let mut out = Self {
167 round_keys: [0u32; 60],
168 };
169 let rk = &mut out.round_keys;
170 for i in 0..8 {
171 rk[i] =
172 u32::from_be_bytes([key[4 * i], key[4 * i + 1], key[4 * i + 2], key[4 * i + 3]]);
173 }
174
175 // `i % 8` depends only on the public loop index, never on key bytes.
176 for i in 8..60 {
177 let mut temp = rk[i - 1];
178 if i % 8 == 0 {
179 temp = sub_word(rot_word(temp)) ^ RCON[(i / 8) - 1];
180 } else if i % 8 == 4 {
181 temp = sub_word(temp);
182 }
183 rk[i] = rk[i - 8] ^ temp;
184 }
185
186 out
187 }
188
189 /// Encrypt a single 16-byte block in place per FIPS 197.
190 ///
191 /// Works directly on the caller's buffer, so no intermediate state copy
192 /// is left on the stack.
193 pub fn encrypt_block(&self, block: &mut [u8; 16]) {
194 let state = block;
195
196 // Initial round: AddRoundKey
197 Self::add_round_key(state, &self.round_keys[0..4]);
198
199 // Rounds 1 to 13
200 for round in 1..14 {
201 Self::sub_bytes(state);
202 Self::shift_rows(state);
203 Self::mix_columns(state);
204 Self::add_round_key(state, &self.round_keys[round * 4..(round + 1) * 4]);
205 }
206
207 // Final round 14 (no MixColumns)
208 Self::sub_bytes(state);
209 Self::shift_rows(state);
210 Self::add_round_key(state, &self.round_keys[14 * 4..15 * 4]);
211 }
212
213 #[inline(always)]
214 fn add_round_key(state: &mut [u8; 16], rk: &[u32]) {
215 for c in 0..4 {
216 let word_bytes = rk[c].to_be_bytes();
217 state[c * 4] ^= word_bytes[0];
218 state[c * 4 + 1] ^= word_bytes[1];
219 state[c * 4 + 2] ^= word_bytes[2];
220 state[c * 4 + 3] ^= word_bytes[3];
221 }
222 }
223
224 #[inline(always)]
225 fn sub_bytes(state: &mut [u8; 16]) {
226 *state = sub_bytes_ct(u128::from_le_bytes(*state)).to_le_bytes();
227 }
228
229 #[inline(always)]
230 fn shift_rows(state: &mut [u8; 16]) {
231 // State is stored column-major:
232 // state[0] state[4] state[8] state[12]
233 // state[1] state[5] state[9] state[13]
234 // state[2] state[6] state[10] state[14]
235 // state[3] state[7] state[11] state[15]
236 let s1 = state[1];
237 state[1] = state[5];
238 state[5] = state[9];
239 state[9] = state[13];
240 state[13] = s1;
241
242 let s2 = state[2];
243 let s6 = state[6];
244 state[2] = state[10];
245 state[6] = state[14];
246 state[10] = s2;
247 state[14] = s6;
248
249 let s3 = state[15];
250 state[15] = state[11];
251 state[11] = state[7];
252 state[7] = state[3];
253 state[3] = s3;
254 }
255
256 #[inline(always)]
257 fn mix_columns(state: &mut [u8; 16]) {
258 for c in 0..4 {
259 let idx = c * 4;
260 let s0 = state[idx];
261 let s1 = state[idx + 1];
262 let s2 = state[idx + 2];
263 let s3 = state[idx + 3];
264
265 let h0 = xtime(s0);
266 let h1 = xtime(s1);
267 let h2 = xtime(s2);
268 let h3 = xtime(s3);
269
270 state[idx] = h0 ^ s1 ^ h1 ^ s2 ^ s3;
271 state[idx + 1] = s0 ^ h1 ^ s2 ^ h2 ^ s3;
272 state[idx + 2] = s0 ^ s1 ^ h2 ^ s3 ^ h3;
273 state[idx + 3] = s0 ^ h0 ^ s1 ^ s2 ^ h3;
274 }
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 /// Reference Rijndael S-box from FIPS 197 Figure 7, used only to check `sub_bytes_ct`.
283 #[rustfmt::skip]
284 const SBOX: [u8; 256] = [
285 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76,
286 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0,
287 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15,
288 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75,
289 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84,
290 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf,
291 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8,
292 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2,
293 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73,
294 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb,
295 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79,
296 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08,
297 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a,
298 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e,
299 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf,
300 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16,
301 ];
302
303 #[test]
304 fn test_constant_time_sbox_matches_fips197_table() {
305 for b in 0..=255u8 {
306 assert_eq!(
307 sbox_ct(b),
308 SBOX[b as usize],
309 "S-box mismatch at input {b:#04x}"
310 );
311 }
312 // All 16 lanes at once, with every lane holding a different input.
313 for base in (0..=255u8).step_by(16) {
314 let mut input = [0u8; 16];
315 for (i, v) in input.iter_mut().enumerate() {
316 *v = base.wrapping_add(i as u8);
317 }
318 let out = sub_bytes_ct(u128::from_le_bytes(input)).to_le_bytes();
319 for i in 0..16 {
320 assert_eq!(out[i], SBOX[input[i] as usize]);
321 }
322 }
323 }
324
325 #[test]
326 fn test_aes_256_fips_197_c2() {
327 // NIST FIPS 197 Appendix C.2 Test Vector (AES-256)
328 let key: [u8; 32] = [
329 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d,
330 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b,
331 0x1c, 0x1d, 0x1e, 0x1f,
332 ];
333 let mut block: [u8; 16] = [
334 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd,
335 0xee, 0xff,
336 ];
337 let expected: [u8; 16] = [
338 0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49,
339 0x60, 0x89,
340 ];
341
342 let cipher = Aes256Key::new(&key);
343 cipher.encrypt_block(&mut block);
344 assert_eq!(block, expected);
345 }
346}