arnaucube
arnaucube/plonky2-crypto-gadgetsPublic Self-hosted repository
plonky2-crypto-gadgets/poseidon-cipher/src/lib.rs
poseidon-cipher/src/lib.rsRaw
  1//! For LICENSE check out https://github.com/0xPARC/plonky2-crypto-gadgets/blob/main/LICENSE
  2//!
  3//! Implements Poseidon encryption as described at
  4//! https://drive.google.com/file/d/1EVrP3DzoGbmzkRmYnyEDcIQcXVU7GlOd/view .
  5
  6#![allow(incomplete_features)]
  7#![feature(generic_const_exprs)]
  8#![allow(dead_code)] // TMP
  9#![allow(non_snake_case)]
 10
 11use std::array;
 12
 13use num::bigint::BigUint;
 14use num_bigint::RandBigInt;
 15use plonky2::{
 16    field::{
 17        extension::{FieldExtension, quintic::QuinticExtension},
 18        goldilocks_field::GoldilocksField as F,
 19        types::Field,
 20    },
 21    hash::{hashing::hash_n_to_m_no_pad, poseidon::PoseidonPermutation},
 22};
 23use pod2::backends::plonky2::primitives::ec::curve::{GROUP_ORDER, Point};
 24use rand::rngs::OsRng;
 25
 26pub mod circuit;
 27
 28// ECField
 29type Fq = QuinticExtension<F>;
 30
 31pub fn new_key() -> (BigUint, Point) {
 32    let k: BigUint = OsRng.gen_biguint_below(&GROUP_ORDER);
 33    let K = &k * Point::generator();
 34    (k, K)
 35}
 36pub fn expanded_key(K: Point) -> Point {
 37    let r: BigUint = OsRng.gen_biguint_below(&GROUP_ORDER);
 38    &r * K
 39}
 40
 41pub(crate) fn two_128() -> Fq {
 42    // WIP TODO
 43    let two32 = Fq::from(F::from_canonical_u64(2_u64.pow(32)));
 44    // dbg!(2_u64.pow(32));
 45    // dbg!(F::from_canonical_u64(2_u64.pow(32)));
 46    // dbg!(&two32);
 47    let two64: Fq = two32 * two32;
 48    // dbg!(&two64);
 49    let two128: Fq = two64 * two64;
 50    // dbg!(&two128);
 51    two128
 52}
 53
 54pub fn encrypt(ks: Point, msg: &[Fq], nonce: [F; 2]) -> Vec<Fq> {
 55    let mut m = msg.to_vec(); // pad m
 56    m.resize(m.len().next_multiple_of(3), Fq::ZERO);
 57
 58    let l = Fq::from(F::from_canonical_u64(msg.len() as u64));
 59    let nonce_5: [F; 5] = [nonce[0], nonce[1], F::ZERO, F::ZERO, F::ZERO];
 60    let n = Fq::from_basefield_array(nonce_5);
 61    let nl128: Fq = n + l * two_128();
 62    let mut s: [Fq; 4] = [Fq::ZERO, ks.x, ks.u, nl128];
 63
 64    let mut ct: Vec<Fq> = vec![Fq::ZERO; m.len() + 1];
 65    for i in 0..m.len() / 3 {
 66        s = hash_state(s);
 67
 68        // absorb
 69        s[1] += m[i * 3];
 70        s[2] += m[i * 3 + 1];
 71        s[3] += m[i * 3 + 2];
 72
 73        // release
 74        ct[i * 3] = s[1];
 75        ct[i * 3 + 1] = s[2];
 76        ct[i * 3 + 2] = s[3];
 77    }
 78    s = hash_state(s);
 79    ct[m.len()] = s[1];
 80    ct
 81}
 82
 83pub fn decrypt(ks: Point, ct: &[Fq], nonce: [F; 2], l: usize) -> Vec<Fq> {
 84    let l_fq = Fq::from(F::from_canonical_u64(l as u64));
 85    let nonce_5: [F; 5] = [nonce[0], nonce[1], F::ZERO, F::ZERO, F::ZERO];
 86    let n = Fq::from_basefield_array(nonce_5);
 87    let nl128: Fq = n + l_fq * two_128();
 88    let mut s: [Fq; 4] = [Fq::ZERO, ks.x, ks.u, nl128];
 89
 90    let mut m: Vec<Fq> = vec![Fq::ZERO; ct.len() - 1];
 91    for i in 0..ct.len() / 3 {
 92        s = hash_state(s);
 93
 94        // release
 95        m[3 * i] = ct[3 * i] - s[1];
 96        m[3 * i + 1] = ct[3 * i + 1] - s[2];
 97        m[3 * i + 2] = ct[3 * i + 2] - s[3];
 98
 99        // modify state
100        s[1] = ct[3 * i];
101        s[2] = ct[3 * i + 1];
102        s[3] = ct[3 * i + 2];
103    }
104
105    if l > 3 {
106        if l % 3 == 2 {
107            assert_eq!(m[m.len() - 1], Fq::ZERO);
108        } else if l % 3 == 1 {
109            assert_eq!(m[m.len() - 1], Fq::ZERO);
110            assert_eq!(m[m.len() - 2], Fq::ZERO);
111        }
112    }
113    s = hash_state(s);
114    assert_eq!(ct[ct.len() - 1], s[1]);
115    m[0..l].to_vec()
116}
117
118fn hash_state(s: [Fq; 4]) -> [Fq; 4] {
119    let elems: [F; 4 * 5] = array::from_fn(|i| s[i / 5].0[i % 5]);
120    // Note: here we're using plonky2's normal poseidon, not duplex-sponge
121    let h = hash_n_to_m_no_pad::<F, PoseidonPermutation<_>>(&elems, 4 * 5);
122    array::from_fn(|i| Fq::from_basefield_array(array::from_fn::<_, 5, _>(|j| h[j + 5 * i])))
123}
124
125#[cfg(test)]
126mod tests {
127    use plonky2::field::types::Sample;
128
129    use super::*;
130
131    #[test]
132    fn test_encrypt_decrypt() {
133        test_encrypt_decrypt_op(9);
134        test_encrypt_decrypt_op(10);
135        test_encrypt_decrypt_op(11);
136        test_encrypt_decrypt_op(12);
137        test_encrypt_decrypt_op(128);
138        test_encrypt_decrypt_op(129);
139        test_encrypt_decrypt_op(1024);
140        test_encrypt_decrypt_op(1023);
141        test_encrypt_decrypt_op(1025);
142    }
143    fn test_encrypt_decrypt_op(msg_len: usize) {
144        let mut rng = rand::thread_rng();
145
146        let (_k, K) = new_key();
147        let ks = expanded_key(K);
148        let nonce: [F; 2] = [F::rand(), F::rand()];
149        let msg: Vec<Fq> = (0..msg_len).map(|_| Fq::sample(&mut rng)).collect();
150        let l = msg.len();
151
152        let ct = encrypt(ks, &msg, nonce);
153
154        let m = decrypt(ks, &ct, nonce, l);
155        assert_eq!(m, msg);
156        assert_ne!(&msg, &ct[..msg_len]);
157    }
158}