plonky2-crypto-gadgets/aes-gcm/src/native_gcm.rs
aes-gcm/src/native_gcm.rsRaw
1//! For LICENSE check out https://github.com/0xPARC/plonky2-crypto-gadgets/blob/main/LICENSE
2//!
3//! Rust native implementation of [AES-GCM (Galois Counter
4//! Mode)](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf)
5//! having in mind the approach that will be done in-circuit; this means that it
6//! is not written in the most rust idiomatic way, nor memory-efficient, but
7//! simulating the behavior that we will do later inside the circuit.
8//!
9
10use crate::{
11 constants::TAG_LEN,
12 native_aes::{encrypt_block, flatten_state, key_expansion},
13};
14
15/// Section 7.1 from https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
16pub fn encrypt<const NK: usize, const NB: usize, const NR: usize>(
17 key: &[u8; NK * NB],
18 nonce: &[u8; 12],
19 pt: &[u8], // plaintext
20) -> (Vec<u8>, Vec<u8>)
21where
22 [(); 4 * (NR + 1)]:,
23{
24 let a: &[u8] = &[]; // additional authenticated data
25 let expanded_key: [[u8; 4]; 4 * (NR + 1)] = key_expansion::<NK, NB, NR>(key);
26
27 // 1. CIPH_K
28 let h = encrypt_block::<NR>(&[0u8; 16], &expanded_key);
29 let h = flatten_state(h);
30
31 // 2. J_0
32 let j0: [u8; 16] = if nonce.len() * 8 == 96 {
33 // J_0 = IV || 0^31 || 1
34 let mut out = [0u8; 16];
35 out[..12].copy_from_slice(nonce.as_slice());
36 out[12..16].copy_from_slice(&[0x00, 0x00, 0x00, 0x01]);
37 out
38 } else {
39 panic!("unsupported at initial version; nonce.len()=12 (96 bits)");
40 };
41
42 // 3. C=GCTR()
43 let c = gctr(expanded_key, &inc32(j0), pt);
44
45 // 4. u, v
46 // note: c.len() will be x.len(), "L" in the circuit
47 let u: usize = 16 * (c.len() as f64 / 16_f64).ceil() as usize - c.len();
48 let v: usize = 16 * (a.len() as f64 / 16_f64).ceil() as usize - a.len();
49
50 // 5. S = GHASH()
51 let a_len: [u8; 8] = (a.len() * 8).to_be_bytes();
52 let c_len: [u8; 8] = (c.len() * 8).to_be_bytes();
53 let ghash_input = &[
54 a.to_vec(),
55 vec![0u8; v],
56 c.clone(),
57 vec![0u8; u],
58 a_len.to_vec(),
59 c_len.to_vec(),
60 ]
61 .concat();
62 let s = ghash(h, ghash_input);
63
64 // 6. T=MSB(GCTR()))
65 let t = msb_t(TAG_LEN, &gctr(expanded_key, &j0, &s));
66
67 (c, t)
68}
69
70/// GCM-Ctr, Section 6.5, Algorithm 3
71pub(crate) fn gctr<const NR: usize>(
72 key: [[u8; 4]; 4 * (NR + 1)],
73 icb: &[u8; 16],
74 x: &[u8],
75) -> Vec<u8> {
76 if x.is_empty() {
77 return x.to_vec();
78 }
79
80 let n = ((x.len() * 8) as f64 / 128_f64).ceil() as usize;
81
82 let mut y: Vec<Vec<u8>> = vec![];
83 let mut cb_i = *icb;
84 for (i, x_i_raw) in x.chunks(16).enumerate() {
85 if i > 0 {
86 cb_i = inc32(cb_i);
87 }
88
89 let l = x_i_raw.len().min(16);
90 let mut x_i = [0u8; 16];
91 x_i[..l].copy_from_slice(x_i_raw);
92
93 let ciph_cb_i = flatten_state(encrypt_block::<NR>(&cb_i, &key));
94
95 let (y_i, n_bytes) = if i < n && x_i_raw.len() == 16 {
96 (xor_blocks(x_i, ciph_cb_i), 16)
97 } else {
98 // last chunk, might be smaller than 16 bytes
99 let msb_res = msb_t(x_i_raw.len(), ciph_cb_i.as_slice());
100 let l = msb_res.len().min(16);
101 let mut m = [0u8; 16];
102 m[..l].copy_from_slice(&msb_res);
103 (xor_blocks(x_i, m), l)
104 };
105 y.push(y_i[..n_bytes].to_vec());
106 }
107 y.concat()
108}
109
110/// Section 6.4, Algorithm 2
111pub(crate) fn ghash(h: [u8; 16], x: &[u8]) -> [u8; 16] {
112 assert!(x.len().is_multiple_of(16)); // multiple of 128 bits
113 let m = x.len() / 16;
114
115 let mut y = [0u8; 16]; // (128 bits)
116 for i in 0..m {
117 let mut xi = [0u8; 16];
118 xi.clone_from_slice(&x[i * 16..i * 16 + 16]);
119 let y_xi = xor_blocks(y, xi);
120 y = gf_2_128_mul(y_xi, h);
121 }
122 y
123}
124fn xor_blocks(b1: [u8; 16], b2: [u8; 16]) -> [u8; 16] {
125 let mut r = [0u8; 16];
126 for i in 0..16 {
127 r[i] = b1[i] ^ b2[i];
128 }
129 r
130}
131
132/// multiplication of blocks (in GF(2^128)), Algorithm 1, Section 6.3
133pub fn gf_2_128_mul(x: [u8; 16], y: [u8; 16]) -> [u8; 16] {
134 // R = 11100001 || 0^120
135 const R: [u8; 16] = [
136 0xE1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
137 0x00,
138 ];
139
140 let mut z = [0u8; 16];
141 let mut v = y;
142 for i in 0..128 {
143 // xi: i-th bit of x
144 let byte_index = i / 8;
145 let bit_index = 7 - (i % 8);
146 let xi = (x[byte_index] >> bit_index) & 1;
147
148 if xi == 1 {
149 z = xor_blocks(z, v);
150 }
151 let lsb = v[15] & 1;
152 right_shift_one(&mut v);
153 if lsb == 1 {
154 v = xor_blocks(v, R);
155 }
156 }
157 z
158}
159
160// auxiliary version for testing the circuit logic
161pub(crate) fn gf_2_128_mul_circuit_version(
162 x: [[bool; 8]; 16],
163 y: [[bool; 8]; 16],
164) -> [[bool; 8]; 16] {
165 let zero_byte = [false; 8];
166
167 // R: 10000111 || 0^120 (in little-endian)
168 let mut r = [zero_byte; 16];
169 r[0][0] = true;
170 r[0][5] = true;
171 r[0][6] = true;
172 r[0][7] = true;
173
174 let mut z = [zero_byte; 16];
175 let mut v = y;
176 for i in 0..128 {
177 let byte_index = i / 8;
178 let bit_index = 7 - (i % 8);
179 let xi = x[byte_index][bit_index];
180
181 // set z = if xi==1: z^v, else: z
182 for b in 0..16 {
183 for k in 0..8 {
184 let z_xor_v = z[b][k] ^ v[b][k];
185 z[b][k] = if xi { z_xor_v } else { z[b][k] };
186 }
187 }
188
189 let lsb = v[15][0]; // (little-endian)
190 v = right_shift_one_circuit_version(&v);
191
192 // if lsb==1: v=v^R, else: v
193 for b in 0..16 {
194 for k in 0..8 {
195 let v_xor_r = v[b][k] ^ r[b][k];
196 v[b][k] = if lsb { v_xor_r } else { v[b][k] };
197 }
198 }
199 }
200 z
201}
202// method for debugging
203fn bools_to_u8_le(bits: [bool; 8]) -> u8 {
204 bits.iter()
205 .enumerate()
206 .fold(0u8, |acc, (i, &bit)| if bit { acc | (1 << i) } else { acc })
207}
208fn right_shift_one_circuit_version(v: &[[bool; 8]; 16]) -> [[bool; 8]; 16] {
209 let mut r: [[bool; 8]; 16] = *v;
210 let mut carry = false;
211 for i in 0..16 {
212 let current = v[i];
213 let next_carry = current[0];
214 let mut shifted = [false; 8];
215 shifted[..7].copy_from_slice(¤t[1..(7 + 1)]);
216 shifted[7] = carry;
217 r[i] = shifted;
218 carry = next_carry;
219 }
220 r
221}
222
223pub(crate) fn right_shift_one(block: &mut [u8; 16]) {
224 let mut carry = 0u8;
225
226 for byte in block.iter_mut() {
227 let new_carry = *byte & 1;
228 *byte = (*byte >> 1) | (carry << 7);
229 carry = new_carry;
230 }
231}
232
233/// increment the right-most 32 bits of the given block (128 bits). Section 2.
234pub(crate) fn inc32(b: [u8; 16]) -> [u8; 16] {
235 let mut r = b;
236 // counter = last 32bits
237 let counter = u32::from_be_bytes([r[12], r[13], r[14], r[15]]);
238 let incremented = counter.wrapping_add(1);
239 let bytes = incremented.to_be_bytes();
240 r[12..16].copy_from_slice(&bytes);
241 r
242}
243
244/// returns the t left-most (most-significant in BE) bits of the block
245pub(crate) fn msb_t(t_bytes: usize, block: &[u8]) -> Vec<u8> {
246 let t = t_bytes * 8;
247
248 let mut out = Vec::with_capacity(t.div_ceil(8));
249 let mut bits_left = t;
250 for byte in block.iter() {
251 if bits_left == 0 {
252 break;
253 }
254 if bits_left >= 8 {
255 out.push(*byte);
256 bits_left -= 8;
257 } else {
258 // take the top `bits_left` bits of the byte
259 let mask = 0xFFu8 << (8 - bits_left);
260 out.push(byte & mask);
261 break;
262 }
263 }
264 out
265}
266
267#[cfg(test)]
268mod tests {
269 use aes_gcm::{
270 Aes128Gcm, Aes256Gcm, Nonce,
271 aead::{Aead, KeyInit},
272 };
273 use rand::Rng;
274
275 use super::*;
276
277 fn hex_to_array<const N: usize>(h: &str) -> [u8; N] {
278 let bytes = hex::decode(h).unwrap();
279 assert_eq!(bytes.len(), N);
280 let mut r: [u8; N] = [0u8; N];
281 r.copy_from_slice(&bytes);
282 r
283 }
284
285 #[test]
286 fn test_aes_gcm_encrypt_nist_vector() {
287 // https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/CAVP-TESTING-BLOCK-CIPHER-MODES
288
289 // test vector from line 7
290 let key: [u8; 16] = hex_to_array("cf063a34d4a9a76c2c86787d3f96db71");
291 let iv: [u8; 12] = hex_to_array("113b9785971864c83b01c787");
292 let pt = [];
293 let expected_c: &[u8] = &[];
294 let expected_tag: [u8; 16] = hex_to_array("72ac8493e3a5228b5d130a69d2510e42");
295 let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
296 assert_eq!(c, expected_c);
297 assert_eq!(tag, expected_tag);
298
299 // test vector from line 4417
300 let key: [u8; 16] = hex_to_array("e98b72a9881a84ca6b76e0f43e68647a");
301 let iv: [u8; 12] = hex_to_array("8b23299fde174053f3d652ba");
302 let pt: [u8; 16] = hex_to_array("28286a321293253c3e0aa2704a278032");
303 let expected_c: [u8; 16] = hex_to_array("5a3c1cf1985dbb8bed818036fdd5ab42");
304 let expected_tag: [u8; 16] = hex_to_array("23c7ab0f952b7091cd324835043b5eb5");
305 let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
306 assert_eq!(c, expected_c);
307 assert_eq!(tag, expected_tag);
308
309 // test vector from line 8834
310 let key: [u8; 16] = hex_to_array("387218b246c1a8257748b56980e50c94");
311 let iv: [u8; 12] = hex_to_array("dd7e014198672be39f95b69d");
312 let expected_c: [u8; 13] = hex_to_array("cdba9e73eaf3d38eceb2b04a8d");
313 let expected_tag: [u8; 16] = hex_to_array("ecf90f4a47c9c626d6fb2c765d201556");
314 let pt: [u8; 13] = hex_to_array("48f5b426baca03064554cc2b30");
315 let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
316 assert_eq!(c, expected_c);
317 assert_eq!(tag, expected_tag);
318
319 // test vector from line 13237
320 let key: [u8; 16] = hex_to_array("bfd414a6212958a607a0f5d3ab48471d");
321 let iv: [u8; 12] = hex_to_array("86d8ea0ab8e40dcc481cd0e2");
322 let expected_c: [u8; 32] =
323 hex_to_array("62171db33193292d930bf6647347652c1ef33316d7feca99d54f1db4fcf513f8");
324 let expected_tag: [u8; 16] = hex_to_array("c28280aa5c6c7a8bd366f28c1cfd1f6e");
325 let pt: [u8; 32] =
326 hex_to_array("a6b76a066e63392c9443e60272ceaeb9d25c991b0f2e55e2804e168c05ea591a");
327 let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
328 assert_eq!(c, expected_c);
329 assert_eq!(tag, expected_tag);
330 }
331
332 /// test checking against external aes-gcm lib
333 #[test]
334 fn test_with_external_lib() -> anyhow::Result<()> {
335 test_with_external_lib_op::<4, 4, 10, Aes128Gcm>()?;
336 test_with_external_lib_op::<8, 4, 14, Aes256Gcm>()
337 }
338 fn test_with_external_lib_op<const NK: usize, const NB: usize, const NR: usize, C>()
339 -> anyhow::Result<()>
340 where
341 [(); NK * NB]:,
342 [(); 4 * (NR + 1)]:,
343 C: KeyInit + Aead,
344 {
345 let key: &[u8; NK * NB] = &[42; NK * NB];
346 let nonce: &[u8; 12] = &[111; 12];
347 let pt: Vec<Vec<u8>> = vec![
348 vec![42u8; 0],
349 vec![42u8; 16],
350 vec![42u8; 32],
351 vec![42u8; 1],
352 vec![42u8; 17],
353 b"test plaintext".to_vec(),
354 b"test plaintext for AES-GCM".to_vec(),
355 rand_bytes(131),
356 rand_bytes(1027),
357 rand_bytes(4242),
358 ];
359
360 let nonce_ext = Nonce::from_slice(nonce);
361 let cipher = C::new_from_slice(key.as_slice()).unwrap();
362
363 for pt_i in pt.iter() {
364 let ciphertext = cipher.encrypt(nonce_ext, pt_i.as_ref()).unwrap();
365
366 let plaintext = cipher.decrypt(nonce_ext, ciphertext.as_ref()).unwrap();
367 assert_eq!(plaintext, *pt_i);
368
369 let (c, t) = encrypt::<NK, NB, NR>(key, nonce, pt_i);
370 assert_eq!(c.len() + t.len(), ciphertext.len());
371 assert_eq!([c, t].concat(), ciphertext);
372 }
373 Ok(())
374 }
375 fn rand_bytes(n: usize) -> Vec<u8> {
376 let mut v = vec![0u8; n];
377 rand::rng().fill_bytes(&mut v);
378 v
379 }
380}