arnaucube
arnaucube/plonky2-crypto-gadgetsPublic Self-hosted repository
plonky2-crypto-gadgets/src/native_gcm.rs
src/native_gcm.rsRaw
  1//! For LICENSE check out https://github.com/0xPARC/plonky2-aes/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::native_aes::{encrypt_block, flatten_state, key_expansion};
 11
 12// supported tag length
 13pub const TAG_LEN: usize = 128;
 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 // TODO maybe as input
 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!("unsuported 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][7].clone();
190        let lsb = v[15][0].clone(); // (little-endian)
191        v = right_shift_one_circuit_version(&v);
192
193        // if lsb==1: v=v^R, else: v
194        for b in 0..16 {
195            for k in 0..8 {
196                let v_xor_r = v[b][k] ^ r[b][k];
197                v[b][k] = if lsb { v_xor_r } else { v[b][k] };
198            }
199        }
200    }
201    z
202}
203// method for debugging
204fn bools_to_u8_le(bits: [bool; 8]) -> u8 {
205    bits.iter()
206        .enumerate()
207        .fold(0u8, |acc, (i, &bit)| if bit { acc | (1 << i) } else { acc })
208}
209fn right_shift_one_circuit_version(v: &[[bool; 8]; 16]) -> [[bool; 8]; 16] {
210    let mut r: [[bool; 8]; 16] = v.clone();
211    let mut carry = false;
212    for i in 0..16 {
213        let current = v[i];
214        let next_carry = current[0];
215        let mut shifted = [false; 8];
216        for j in 0..7 {
217            shifted[j] = current[j + 1];
218        }
219        shifted[7] = carry;
220        r[i] = shifted;
221        carry = next_carry;
222    }
223    r
224}
225
226pub(crate) fn right_shift_one(block: &mut [u8; 16]) {
227    let mut carry = 0u8;
228
229    for byte in block.iter_mut() {
230        let new_carry = *byte & 1;
231        *byte = (*byte >> 1) | (carry << 7);
232        carry = new_carry;
233    }
234}
235
236/// increment the right-most 32 bits of the given block (128 bits). Section 2.
237pub(crate) fn inc32(b: [u8; 16]) -> [u8; 16] {
238    let mut r = b;
239    // counter = last 32bits
240    let counter = u32::from_be_bytes([r[12], r[13], r[14], r[15]]);
241    let incremented = counter.wrapping_add(1);
242    let bytes = incremented.to_be_bytes();
243    r[12..16].copy_from_slice(&bytes);
244    r
245}
246
247/// returns the t left-most (most-significant in BE) bits of the block
248pub(crate) fn msb_t(t_bytes: usize, block: &[u8]) -> Vec<u8> {
249    let t = t_bytes * 8;
250
251    let mut out = Vec::with_capacity(t.div_ceil(8));
252    let mut bits_left = t;
253    for byte in block.iter() {
254        if bits_left == 0 {
255            break;
256        }
257        if bits_left >= 8 {
258            out.push(*byte);
259            bits_left -= 8;
260        } else {
261            // take the top `bits_left` bits of the byte
262            let mask = 0xFFu8 << (8 - bits_left);
263            out.push(byte & mask);
264            break;
265        }
266    }
267    out
268}
269
270#[cfg(test)]
271mod tests {
272    use super::*;
273
274    use aes_gcm::{
275        aead::{Aead, KeyInit},
276        Aes128Gcm, Aes256Gcm, Nonce,
277    };
278    use rand::Rng;
279
280    fn hex_to_array<const N: usize>(h: &str) -> [u8; N] {
281        let bytes = hex::decode(h).unwrap();
282        assert_eq!(bytes.len(), N);
283        let mut r: [u8; N] = [0u8; N];
284        r.copy_from_slice(&bytes);
285        r
286    }
287
288    #[test]
289    fn test_aes_gcm_encrypt_nist_vector() {
290        // https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/CAVP-TESTING-BLOCK-CIPHER-MODES
291
292        // test vector from line 7
293        let key: [u8; 16] = hex_to_array("cf063a34d4a9a76c2c86787d3f96db71");
294        let iv: [u8; 12] = hex_to_array("113b9785971864c83b01c787");
295        let pt = [];
296        let expected_c: &[u8] = &[];
297        let expected_tag: [u8; 16] = hex_to_array("72ac8493e3a5228b5d130a69d2510e42");
298        let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
299        assert_eq!(c, expected_c);
300        assert_eq!(tag, expected_tag);
301
302        // test vector from line 4417
303        let key: [u8; 16] = hex_to_array("e98b72a9881a84ca6b76e0f43e68647a");
304        let iv: [u8; 12] = hex_to_array("8b23299fde174053f3d652ba");
305        let pt: [u8; 16] = hex_to_array("28286a321293253c3e0aa2704a278032");
306        let expected_c: [u8; 16] = hex_to_array("5a3c1cf1985dbb8bed818036fdd5ab42");
307        let expected_tag: [u8; 16] = hex_to_array("23c7ab0f952b7091cd324835043b5eb5");
308        let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
309        assert_eq!(c, expected_c);
310        assert_eq!(tag, expected_tag);
311
312        // test vector from line 8834
313        let key: [u8; 16] = hex_to_array("387218b246c1a8257748b56980e50c94");
314        let iv: [u8; 12] = hex_to_array("dd7e014198672be39f95b69d");
315        let expected_c: [u8; 13] = hex_to_array("cdba9e73eaf3d38eceb2b04a8d");
316        let expected_tag: [u8; 16] = hex_to_array("ecf90f4a47c9c626d6fb2c765d201556");
317        let pt: [u8; 13] = hex_to_array("48f5b426baca03064554cc2b30");
318        let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
319        assert_eq!(c, expected_c);
320        assert_eq!(tag, expected_tag);
321
322        // test vector from line 13237
323        let key: [u8; 16] = hex_to_array("bfd414a6212958a607a0f5d3ab48471d");
324        let iv: [u8; 12] = hex_to_array("86d8ea0ab8e40dcc481cd0e2");
325        let expected_c: [u8; 32] =
326            hex_to_array("62171db33193292d930bf6647347652c1ef33316d7feca99d54f1db4fcf513f8");
327        let expected_tag: [u8; 16] = hex_to_array("c28280aa5c6c7a8bd366f28c1cfd1f6e");
328        let pt: [u8; 32] =
329            hex_to_array("a6b76a066e63392c9443e60272ceaeb9d25c991b0f2e55e2804e168c05ea591a");
330        let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
331        assert_eq!(c, expected_c);
332        assert_eq!(tag, expected_tag);
333    }
334
335    /// test checking against external aes-gcm lib
336    #[test]
337    fn test_with_external_lib() -> anyhow::Result<()> {
338        test_with_external_lib_op::<4, 4, 10, Aes128Gcm>()?;
339        test_with_external_lib_op::<8, 4, 14, Aes256Gcm>()
340    }
341    fn test_with_external_lib_op<const NK: usize, const NB: usize, const NR: usize, C>(
342    ) -> anyhow::Result<()>
343    where
344        [(); NK * NB]:,
345        [(); 4 * (NR + 1)]:,
346        C: KeyInit + Aead,
347    {
348        let key: &[u8; NK * NB] = &[42; NK * NB];
349        let nonce: &[u8; 12] = &[111; 12];
350        let pt: Vec<Vec<u8>> = vec![
351            vec![42u8; 0],
352            vec![42u8; 16],
353            vec![42u8; 32],
354            vec![42u8; 1],
355            vec![42u8; 17],
356            b"test plaintext".to_vec(),
357            b"test plaintext for AES-GCM".to_vec(),
358            rand_bytes(131),
359            rand_bytes(1027),
360            rand_bytes(4242),
361        ];
362
363        let nonce_ext = Nonce::from_slice(nonce);
364        let cipher = C::new_from_slice(key.as_slice()).unwrap();
365
366        for pt_i in pt.iter() {
367            let ciphertext = cipher.encrypt(nonce_ext, pt_i.as_ref()).unwrap();
368
369            let plaintext = cipher.decrypt(nonce_ext, ciphertext.as_ref()).unwrap();
370            assert_eq!(plaintext, *pt_i);
371
372            let (c, t) = encrypt::<NK, NB, NR>(key, nonce, pt_i);
373            assert_eq!(c.len() + t.len(), ciphertext.len());
374            assert_eq!([c, t].concat(), ciphertext);
375        }
376        Ok(())
377    }
378    fn rand_bytes(n: usize) -> Vec<u8> {
379        let mut v = vec![0u8; n];
380        rand::rng().fill_bytes(&mut v);
381        v
382    }
383}