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_gcm_siv.rs

346 lines · 11900 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-GCM-SIV AEAD implementation conforming to RFC 8452.
17//!
18//! Nonce-misuse-resistant authenticated encryption with associated data (AEAD)
19//! using 256-bit keys, 96-bit nonces, and 128-bit authentication tags.
20//!
21//! Secret intermediates (derived keys, key-derivation scratch, CTR keystream,
22//! padded plaintext tails) live in self-wiping buffers, so they are zeroed on
23//! every return path, including authentication failure.
24
25use crate::aes::Aes256Key;
26use crate::polyval::Polyval;
27use crate::Secret;
28
29/// Tag size in bytes (128 bits).
30pub const TAG_LEN: usize = 16;
31/// Nonce size in bytes (96 bits).
32pub const NONCE_LEN: usize = 12;
33/// Key size in bytes (256 bits).
34pub const KEY_LEN: usize = 32;
35
36/// Error returned when decryption authentication verification fails.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38pub struct AuthenticationError;
39
40/// Derive the 128-bit authentication key and 256-bit encryption key per RFC 8452 Section 4.
41///
42/// Both returned buffers wipe themselves on drop, including caller error paths.
43pub fn derive_keys(key: &[u8; 32], nonce: &[u8; 12]) -> (Secret<16>, Secret<32>) {
44 let mut auth_key = Secret::<16>::zeroed();
45 let mut enc_key = Secret::<32>::zeroed();
46 derive_keys_into(key, nonce, &mut auth_key.0, &mut enc_key.0);
47 (auth_key, enc_key)
48}
49
50/// Derive both per-nonce keys into caller-owned buffers. The scratch block is wiped.
51fn derive_keys_into(
52 key: &[u8; 32],
53 nonce: &[u8; 12],
54 auth_key: &mut [u8; 16],
55 enc_key: &mut [u8; 32],
56) {
57 let k_cipher = Aes256Key::new(key);
58 let mut scratch = Secret::<16>::zeroed();
59 let block = &mut scratch.0;
60
61 for i in 0..6u32 {
62 block[0..4].copy_from_slice(&i.to_le_bytes());
63 block[4..16].copy_from_slice(nonce);
64
65 k_cipher.encrypt_block(block);
66
67 match i {
68 0 => auth_key[0..8].copy_from_slice(&block[0..8]),
69 1 => auth_key[8..16].copy_from_slice(&block[0..8]),
70 2 => enc_key[0..8].copy_from_slice(&block[0..8]),
71 3 => enc_key[8..16].copy_from_slice(&block[0..8]),
72 4 => enc_key[16..24].copy_from_slice(&block[0..8]),
73 5 => enc_key[24..32].copy_from_slice(&block[0..8]),
74 _ => unreachable!(),
75 }
76 }
77}
78
79/// Constant-time comparison of two 16-byte tags.
80#[inline(never)]
81fn constant_time_eq_tag(a: &[u8; 16], b: &[u8; 16]) -> bool {
82 let mut diff = 0u8;
83 for i in 0..16 {
84 diff |= a[i] ^ b[i];
85 }
86 diff == 0
87}
88
89/// Compute length block: 64-bit le AAD bit len || 64-bit le plaintext bit len.
90fn make_length_block(aad_len: usize, plaintext_len: usize) -> [u8; 16] {
91 let mut len_block = [0u8; 16];
92 let aad_bits = (aad_len as u64).wrapping_mul(8);
93 let pt_bits = (plaintext_len as u64).wrapping_mul(8);
94 len_block[0..8].copy_from_slice(&aad_bits.to_le_bytes());
95 len_block[8..16].copy_from_slice(&pt_bits.to_le_bytes());
96 len_block
97}
98
99/// Compute SIV tag given auth_key, enc_cipher, nonce, aad, and plaintext.
100fn compute_tag(
101 auth_key: &[u8; 16],
102 enc_cipher: &Aes256Key,
103 nonce: &[u8; 12],
104 aad: &[u8],
105 plaintext: &[u8],
106) -> [u8; 16] {
107 let mut poly = Polyval::new(auth_key);
108
109 // Feed AAD padded to 16-byte boundary
110 let (aad_chunks, aad_rem) = aad.as_chunks::<16>();
111 for chunk in aad_chunks {
112 poly.update_block(chunk);
113 }
114 if !aad_rem.is_empty() {
115 let mut b = Secret::<16>::zeroed();
116 b.0[..aad_rem.len()].copy_from_slice(aad_rem);
117 poly.update_block(&b.0);
118 }
119
120 // Feed plaintext padded to 16-byte boundary
121 let (pt_chunks, pt_rem) = plaintext.as_chunks::<16>();
122 for chunk in pt_chunks {
123 poly.update_block(chunk);
124 }
125 if !pt_rem.is_empty() {
126 // Holds a plaintext tail: wiped on drop.
127 let mut b = Secret::<16>::zeroed();
128 b.0[..pt_rem.len()].copy_from_slice(pt_rem);
129 poly.update_block(&b.0);
130 }
131
132 // Feed length block
133 let len_block = make_length_block(aad.len(), plaintext.len());
134 poly.update_block(&len_block);
135
136 let mut s_s = poly.finalize();
137
138 // XOR first 12 bytes with nonce, clear MSB of last byte
139 for i in 0..12 {
140 s_s[i] ^= nonce[i];
141 }
142 s_s[15] &= 0x7f;
143
144 // Encrypt with enc_key
145 enc_cipher.encrypt_block(&mut s_s);
146 s_s
147}
148
149/// Perform AES-CTR keystream encryption/decryption in place.
150fn apply_ctr(enc_cipher: &Aes256Key, tag: &[u8; 16], buf: &mut [u8]) {
151 let mut counter_block = *tag;
152 counter_block[15] |= 0x80;
153
154 // Keystream bytes are secret (they unmask the plaintext): wiped on drop.
155 let mut keystream = Secret::<16>::zeroed();
156 let mut offset = 0;
157 while offset < buf.len() {
158 keystream.0 = counter_block;
159 enc_cipher.encrypt_block(&mut keystream.0);
160
161 let ctr = u32::from_le_bytes([
162 counter_block[0],
163 counter_block[1],
164 counter_block[2],
165 counter_block[3],
166 ]);
167 counter_block[0..4].copy_from_slice(&ctr.wrapping_add(1).to_le_bytes());
168
169 let todo = core::cmp::min(buf.len() - offset, 16);
170 for i in 0..todo {
171 buf[offset + i] ^= keystream.0[i];
172 }
173 offset += todo;
174 }
175}
176
177/// Encrypt plaintext with AES-256-GCM-SIV per RFC 8452.
178///
179/// Output slice `out_ciphertext_and_tag` must be exactly `plaintext.len() + TAG_LEN` bytes.
180pub fn encrypt(
181 key: &[u8; 32],
182 nonce: &[u8; 12],
183 aad: &[u8],
184 plaintext: &[u8],
185 out_ciphertext_and_tag: &mut [u8],
186) {
187 assert_eq!(
188 out_ciphertext_and_tag.len(),
189 plaintext.len() + TAG_LEN,
190 "Destination buffer must equal plaintext len + 16"
191 );
192
193 // Derived keys live in self-wiping buffers, wiped on every return path.
194 let mut auth_key = Secret::<16>::zeroed();
195 let mut enc_key = Secret::<32>::zeroed();
196 derive_keys_into(key, nonce, &mut auth_key.0, &mut enc_key.0);
197 let enc_cipher = Aes256Key::new(&enc_key.0);
198
199 let tag = compute_tag(&auth_key.0, &enc_cipher, nonce, aad, plaintext);
200
201 // Copy plaintext into output slice, then apply CTR in place
202 out_ciphertext_and_tag[..plaintext.len()].copy_from_slice(plaintext);
203 apply_ctr(
204 &enc_cipher,
205 &tag,
206 &mut out_ciphertext_and_tag[..plaintext.len()],
207 );
208
209 // Append 16-byte tag
210 out_ciphertext_and_tag[plaintext.len()..].copy_from_slice(&tag);
211}
212
213/// Decrypt ciphertext with AES-256-GCM-SIV per RFC 8452.
214///
215/// Plaintext is written to `out_plaintext`, which must be `ciphertext_and_tag.len() - TAG_LEN` bytes.
216/// If authentication fails, `out_plaintext` is zeroed and `Err(AuthenticationError)` is returned.
217pub fn decrypt(
218 key: &[u8; 32],
219 nonce: &[u8; 12],
220 aad: &[u8],
221 ciphertext_and_tag: &[u8],
222 out_plaintext: &mut [u8],
223) -> Result<(), AuthenticationError> {
224 if ciphertext_and_tag.len() < TAG_LEN {
225 return Err(AuthenticationError);
226 }
227 let ciphertext_len = ciphertext_and_tag.len() - TAG_LEN;
228 assert_eq!(
229 out_plaintext.len(),
230 ciphertext_len,
231 "Destination plaintext buffer must equal ciphertext len"
232 );
233
234 let (ciphertext, received_tag_slice) = ciphertext_and_tag.split_at(ciphertext_len);
235 let mut received_tag = [0u8; 16];
236 received_tag.copy_from_slice(received_tag_slice);
237
238 // Derived keys live in self-wiping buffers, wiped on every return path
239 // (success and authentication failure alike).
240 let mut auth_key = Secret::<16>::zeroed();
241 let mut enc_key = Secret::<32>::zeroed();
242 derive_keys_into(key, nonce, &mut auth_key.0, &mut enc_key.0);
243 let enc_cipher = Aes256Key::new(&enc_key.0);
244
245 // Decrypt in place into out_plaintext
246 out_plaintext.copy_from_slice(ciphertext);
247 apply_ctr(&enc_cipher, &received_tag, out_plaintext);
248
249 // Compute expected tag over decrypted plaintext
250 let expected_tag = compute_tag(&auth_key.0, &enc_cipher, nonce, aad, out_plaintext);
251
252 if constant_time_eq_tag(&received_tag, &expected_tag) {
253 Ok(())
254 } else {
255 // Zero decrypted plaintext on failure
256 crate::wipe(out_plaintext);
257 Err(AuthenticationError)
258 }
259}
260
261#[cfg(test)]
262mod tests {
263 use super::*;
264 use std::vec;
265
266 #[test]
267 fn public_derived_keys_are_guarded_and_redacted() {
268 let key = [0x31; KEY_LEN];
269 let nonce = [0x72; NONCE_LEN];
270 let (auth, enc) = derive_keys(&key, &nonce);
271 let mut expected_auth = [0; 16];
272 let mut expected_enc = [0; 32];
273 derive_keys_into(&key, &nonce, &mut expected_auth, &mut expected_enc);
274 assert_eq!(*auth, expected_auth);
275 assert_eq!(*enc, expected_enc);
276 assert_eq!(
277 std::format!("{auth:?} {enc:?}"),
278 "Secret([REDACTED]) Secret([REDACTED])"
279 );
280 crate::wipe(&mut expected_auth);
281 crate::wipe(&mut expected_enc);
282 }
283
284 fn hex_to_vec(hex: &str) -> std::vec::Vec<u8> {
285 let mut v = std::vec::Vec::new();
286 for i in 0..hex.len() / 2 {
287 v.push(u8::from_str_radix(&hex[2 * i..2 * i + 2], 16).unwrap());
288 }
289 v
290 }
291
292 #[test]
293 fn test_rfc8452_appendix_c_aes256_16byte_pt_0byte_aad() {
294 let key_vec =
295 hex_to_vec("0100000000000000000000000000000000000000000000000000000000000000");
296 let nonce_vec = hex_to_vec("030000000000000000000000");
297 let pt_vec = hex_to_vec("01000000000000000000000000000000");
298 let expected_result =
299 hex_to_vec("85a01b63025ba19b7fd3ddfc033b3e76c9eac6fa700942702e90862383c6c366");
300
301 let mut key = [0u8; 32];
302 key.copy_from_slice(&key_vec);
303 let mut nonce = [0u8; 12];
304 nonce.copy_from_slice(&nonce_vec);
305
306 let mut out = vec![0u8; pt_vec.len() + TAG_LEN];
307 encrypt(&key, &nonce, b"", &pt_vec, &mut out);
308 assert_eq!(out, expected_result);
309
310 let mut decrypted = vec![0u8; pt_vec.len()];
311 decrypt(&key, &nonce, b"", &out, &mut decrypted).expect("Decryption failed");
312 assert_eq!(decrypted, pt_vec);
313 }
314
315 #[test]
316 fn test_rfc8452_appendix_c_aes256_8byte_pt_1byte_aad() {
317 let key_vec =
318 hex_to_vec("0100000000000000000000000000000000000000000000000000000000000000");
319 let nonce_vec = hex_to_vec("030000000000000000000000");
320 let pt_vec = hex_to_vec("0200000000000000");
321 let aad_vec = hex_to_vec("01");
322 let expected_result = hex_to_vec("1de22967237a813291213f267e3b452f02d01ae33e4ec854");
323
324 let mut key = [0u8; 32];
325 key.copy_from_slice(&key_vec);
326 let mut nonce = [0u8; 12];
327 nonce.copy_from_slice(&nonce_vec);
328
329 let mut out = vec![0u8; pt_vec.len() + TAG_LEN];
330 encrypt(&key, &nonce, &aad_vec, &pt_vec, &mut out);
331 assert_eq!(out, expected_result);
332
333 let mut decrypted = vec![0u8; pt_vec.len()];
334 decrypt(&key, &nonce, &aad_vec, &out, &mut decrypted).expect("Decryption failed");
335 assert_eq!(decrypted, pt_vec);
336
337 // Tamper test
338 out[0] ^= 0x01;
339 assert_eq!(
340 decrypt(&key, &nonce, &aad_vec, &out, &mut decrypted),
341 Err(AuthenticationError)
342 );
343 // Ensure memory was zeroed on failure
344 assert_eq!(decrypted, vec![0u8; pt_vec.len()]);
345 }
346}