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
 13const 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    let u: usize = 16 * (c.len() as f64 / 16_f64).ceil() as usize - c.len();
 47    let v: usize = 16 * (a.len() as f64 / 16_f64).ceil() as usize - a.len();
 48
 49    // 5. S = GHASH()
 50    let a_len: [u8; 8] = (a.len() * 8).to_be_bytes();
 51    let c_len: [u8; 8] = (c.len() * 8).to_be_bytes();
 52    let ghash_input = &[
 53        a.to_vec(),
 54        vec![0u8; v],
 55        c.clone(),
 56        vec![0u8; u],
 57        a_len.to_vec(),
 58        c_len.to_vec(),
 59    ]
 60    .concat();
 61    let s = ghash(h, ghash_input);
 62
 63    // 6. T=MSB(GCTR()))
 64    let t = msb_t(TAG_LEN, &gctr(expanded_key, &j0, &s));
 65
 66    (c, t)
 67}
 68
 69/// GCM-Ctr, Section 6.5, Algorithm 3
 70pub(crate) fn gctr<const NR: usize>(
 71    key: [[u8; 4]; 4 * (NR + 1)],
 72    icb: &[u8; 16],
 73    x: &[u8],
 74) -> Vec<u8> {
 75    if x.is_empty() {
 76        return x.to_vec();
 77    }
 78
 79    let n = ((x.len() * 8) as f64 / 128_f64).ceil() as usize;
 80
 81    let mut y: Vec<Vec<u8>> = vec![];
 82    let mut cb_i = *icb;
 83    for (i, x_i_raw) in x.chunks(16).enumerate() {
 84        if i > 0 {
 85            cb_i = inc32(cb_i);
 86        }
 87
 88        let l = x_i_raw.len().min(16);
 89        let mut x_i = [0u8; 16];
 90        x_i[..l].copy_from_slice(x_i_raw);
 91
 92        let ciph_cb_i = flatten_state(encrypt_block::<NR>(&cb_i, &key));
 93
 94        let (y_i, n_bytes) = if i < n && x_i_raw.len() == 16 {
 95            (xor_blocks(x_i, ciph_cb_i), 16)
 96        } else {
 97            // last chunk, might be smaller than 16 bytes
 98            let msb_res = msb_t(x_i_raw.len(), ciph_cb_i.as_slice());
 99            let l = msb_res.len().min(16);
100            let mut m = [0u8; 16];
101            m[..l].copy_from_slice(&msb_res);
102            (xor_blocks(x_i, m), l)
103        };
104        y.push(y_i[..n_bytes].to_vec());
105    }
106    y.concat()
107}
108
109/// Section 6.4, Algorithm 2
110pub(crate) fn ghash(h: [u8; 16], x: &[u8]) -> [u8; 16] {
111    assert!(x.len().is_multiple_of(16)); // multiple of 128 bits
112    let m = x.len() / 16;
113
114    let mut y = [0u8; 16]; // (128 bits)
115    for i in 0..m {
116        let mut xi = [0u8; 16];
117        xi.clone_from_slice(&x[i * 16..i * 16 + 16]);
118        let y_xi = xor_blocks(y, xi);
119        y = gf_2_128_mul(y_xi, h);
120    }
121    y
122}
123fn xor_blocks(b1: [u8; 16], b2: [u8; 16]) -> [u8; 16] {
124    let mut r = [0u8; 16];
125    for i in 0..16 {
126        r[i] = b1[i] ^ b2[i];
127    }
128    r
129}
130
131/// multiplication of blocks (in GF(2^128)), Algorithm 1, Section 6.3
132pub fn gf_2_128_mul(x: [u8; 16], y: [u8; 16]) -> [u8; 16] {
133    // R = 11100001 || 0^120
134    const R: [u8; 16] = [
135        0xE1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
136        0x00,
137    ];
138
139    let mut z = [0u8; 16];
140    let mut v = y;
141    for i in 0..128 {
142        // xi: i-th bit of x
143        let byte_index = i / 8;
144        let bit_index = 7 - (i % 8);
145        let xi = (x[byte_index] >> bit_index) & 1;
146
147        if xi == 1 {
148            z = xor_blocks(z, v);
149        }
150        let lsb = v[15] & 1;
151        right_shift_one(&mut v);
152        if lsb == 1 {
153            v = xor_blocks(v, R);
154        }
155    }
156    z
157}
158fn right_shift_one(block: &mut [u8; 16]) {
159    let mut carry = 0u8;
160
161    for byte in block.iter_mut() {
162        let new_carry = *byte & 1;
163        *byte = (*byte >> 1) | (carry << 7);
164        carry = new_carry;
165    }
166}
167
168/// increment the right-most 32 bits of the given block (128 bits). Section 2.
169pub(crate) fn inc32(b: [u8; 16]) -> [u8; 16] {
170    let mut r = b;
171    // counter = last 32bits
172    let counter = u32::from_be_bytes([r[12], r[13], r[14], r[15]]);
173    let incremented = counter.wrapping_add(1);
174    let bytes = incremented.to_be_bytes();
175    r[12..16].copy_from_slice(&bytes);
176    r
177}
178
179/// returns the t left-most (most-significant in BE) bits of the block
180pub(crate) fn msb_t(t_bytes: usize, block: &[u8]) -> Vec<u8> {
181    let t = t_bytes * 8;
182
183    let mut out = Vec::with_capacity(t.div_ceil(8));
184    let mut bits_left = t;
185    for byte in block.iter() {
186        if bits_left == 0 {
187            break;
188        }
189        if bits_left >= 8 {
190            out.push(*byte);
191            bits_left -= 8;
192        } else {
193            // take the top `bits_left` bits of the byte
194            let mask = 0xFFu8 << (8 - bits_left);
195            out.push(byte & mask);
196            break;
197        }
198    }
199    out
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    use aes_gcm::{
207        aead::{Aead, KeyInit},
208        Aes128Gcm, Aes256Gcm, Nonce,
209    };
210    use rand::Rng;
211
212    fn hex_to_array<const N: usize>(h: &str) -> [u8; N] {
213        let bytes = hex::decode(h).unwrap();
214        assert_eq!(bytes.len(), N);
215        let mut r: [u8; N] = [0u8; N];
216        r.copy_from_slice(&bytes);
217        r
218    }
219
220    #[test]
221    fn test_aes_gcm_encrypt_nist_vector() {
222        // https://csrc.nist.gov/Projects/Cryptographic-Algorithm-Validation-Program/CAVP-TESTING-BLOCK-CIPHER-MODES
223
224        // test vector from line 7
225        let key: [u8; 16] = hex_to_array("cf063a34d4a9a76c2c86787d3f96db71");
226        let iv: [u8; 12] = hex_to_array("113b9785971864c83b01c787");
227        let pt = [];
228        let expected_c: &[u8] = &[];
229        let expected_tag: [u8; 16] = hex_to_array("72ac8493e3a5228b5d130a69d2510e42");
230        let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
231        assert_eq!(c, expected_c);
232        assert_eq!(tag, expected_tag);
233
234        // test vector from line 4417
235        let key: [u8; 16] = hex_to_array("e98b72a9881a84ca6b76e0f43e68647a");
236        let iv: [u8; 12] = hex_to_array("8b23299fde174053f3d652ba");
237        let pt: [u8; 16] = hex_to_array("28286a321293253c3e0aa2704a278032");
238        let expected_c: [u8; 16] = hex_to_array("5a3c1cf1985dbb8bed818036fdd5ab42");
239        let expected_tag: [u8; 16] = hex_to_array("23c7ab0f952b7091cd324835043b5eb5");
240        let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
241        assert_eq!(c, expected_c);
242        assert_eq!(tag, expected_tag);
243
244        // test vector from line 8834
245        let key: [u8; 16] = hex_to_array("387218b246c1a8257748b56980e50c94");
246        let iv: [u8; 12] = hex_to_array("dd7e014198672be39f95b69d");
247        let expected_c: [u8; 13] = hex_to_array("cdba9e73eaf3d38eceb2b04a8d");
248        let expected_tag: [u8; 16] = hex_to_array("ecf90f4a47c9c626d6fb2c765d201556");
249        let pt: [u8; 13] = hex_to_array("48f5b426baca03064554cc2b30");
250        let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
251        assert_eq!(c, expected_c);
252        assert_eq!(tag, expected_tag);
253
254        // test vector from line 13237
255        let key: [u8; 16] = hex_to_array("bfd414a6212958a607a0f5d3ab48471d");
256        let iv: [u8; 12] = hex_to_array("86d8ea0ab8e40dcc481cd0e2");
257        let expected_c: [u8; 32] =
258            hex_to_array("62171db33193292d930bf6647347652c1ef33316d7feca99d54f1db4fcf513f8");
259        let expected_tag: [u8; 16] = hex_to_array("c28280aa5c6c7a8bd366f28c1cfd1f6e");
260        let pt: [u8; 32] =
261            hex_to_array("a6b76a066e63392c9443e60272ceaeb9d25c991b0f2e55e2804e168c05ea591a");
262        let (c, tag) = encrypt::<4, 4, 10>(&key, &iv, &pt);
263        assert_eq!(c, expected_c);
264        assert_eq!(tag, expected_tag);
265    }
266
267    /// test checking against external aes-gcm lib
268    #[test]
269    fn test_with_external_lib() -> anyhow::Result<()> {
270        test_with_external_lib_op::<4, 4, 10, Aes128Gcm>()?;
271        test_with_external_lib_op::<8, 4, 14, Aes256Gcm>()
272    }
273    fn test_with_external_lib_op<const NK: usize, const NB: usize, const NR: usize, C>(
274    ) -> anyhow::Result<()>
275    where
276        [(); NK * NB]:,
277        [(); 4 * (NR + 1)]:,
278        C: KeyInit + Aead,
279    {
280        let key: &[u8; NK * NB] = &[42; NK * NB];
281        let nonce: &[u8; 12] = &[111; 12];
282        let pt: Vec<Vec<u8>> = vec![
283            vec![42u8; 0],
284            vec![42u8; 16],
285            vec![42u8; 32],
286            vec![42u8; 1],
287            vec![42u8; 17],
288            b"test plaintext".to_vec(),
289            b"test plaintext for AES-GCM".to_vec(),
290            rand_bytes(131),
291            rand_bytes(1027),
292            rand_bytes(4242),
293        ];
294
295        let nonce_ext = Nonce::from_slice(nonce);
296        let cipher = C::new_from_slice(key.as_slice()).unwrap();
297
298        for pt_i in pt.iter() {
299            let ciphertext = cipher.encrypt(nonce_ext, pt_i.as_ref()).unwrap();
300
301            let plaintext = cipher.decrypt(nonce_ext, ciphertext.as_ref()).unwrap();
302            assert_eq!(plaintext, *pt_i);
303
304            let (c, t) = encrypt::<NK, NB, NR>(key, nonce, pt_i);
305            assert_eq!(c.len() + t.len(), ciphertext.len());
306            assert_eq!([c, t].concat(), ciphertext);
307        }
308        Ok(())
309    }
310    fn rand_bytes(n: usize) -> Vec<u8> {
311        let mut v = vec![0u8; n];
312        rand::rng().fill_bytes(&mut v);
313        v
314    }
315}