use anyhow::Result; use itertools::zip_eq; use rand::distributions::Standard; use rand::Rng; use rand_distr::{Normal, Uniform}; use std::array; use std::iter::Sum; use std::ops::{Add, AddAssign, Mul, Sub}; use arith::{Ring, Rq, Tn, Zq, T64, TR}; const ERR_SIGMA: f64 = 3.2; #[derive(Clone, Debug)] pub struct TLWE(TR, K>, Tn<1>); #[derive(Clone, Debug)] pub struct SecretKey(TR, K>); #[derive(Clone, Debug)] pub struct PublicKey(Tn<1>, TR, K>); impl TLWE { pub fn zero() -> Self { Self(TR::zero(), Tn::zero()) } pub fn new_key(mut rng: impl Rng) -> Result<(SecretKey, PublicKey)> { let Xi_key = Uniform::new(0_f64, 2_f64); let Xi_err = Normal::new(0_f64, ERR_SIGMA)?; let s: TR, K> = TR::rand(&mut rng, Xi_key); let a: TR, K> = TR::rand(&mut rng, Standard); let e = Tn::rand(&mut rng, Xi_err); let pk: PublicKey = PublicKey((&a * &s) + e, a); Ok((SecretKey(s), pk)) } pub fn encode(m: Rq) -> Tn<1> { let delta = u64::MAX / P; // floored let coeffs = m.coeffs(); Tn(array::from_fn(|i| T64(coeffs[i].0 * delta))) } pub fn decode(p: Tn<1>) -> Rq { let p = p.mul_div_round(P, u64::MAX); Rq::::from_vec_u64(p.coeffs().iter().map(|c| c.0).collect()) } // encrypts with the given SecretKey (instead of PublicKey) pub fn encrypt_s(mut rng: impl Rng, sk: &SecretKey, m: &Tn<1>) -> Result { let Xi_key = Uniform::new(0_f64, 2_f64); let Xi_err = Normal::new(0_f64, ERR_SIGMA)?; let a: TR, K> = TR::rand(&mut rng, Xi_key); let e = Tn::rand(&mut rng, Xi_err); let b: Tn<1> = (&a * &sk.0) + *m + e; Ok(Self(a, b)) } pub fn encrypt(mut rng: impl Rng, pk: &PublicKey, m: &Tn<1>) -> Result { let Xi_key = Uniform::new(0_f64, 2_f64); let Xi_err = Normal::new(0_f64, ERR_SIGMA)?; let u: Tn<1> = Tn::rand(&mut rng, Xi_key); let e0: Tn<1> = Tn::rand(&mut rng, Xi_err); let e1 = TR::, K>::rand(&mut rng, Xi_err); let b: Tn<1> = pk.0 * u + *m + e0; let d: TR, K> = &pk.1 * &u + e1; Ok(Self(d, b)) } pub fn decrypt(&self, sk: &SecretKey) -> Tn<1> { let (d, b): (TR, K>, Tn<1>) = (self.0.clone(), self.1); b - &d * &sk.0 } } #[cfg(test)] mod tests { use anyhow::Result; use rand::distributions::Uniform; use super::*; #[test] fn test_encrypt_decrypt() -> Result<()> { const T: u64 = 32; // plaintext modulus const K: usize = 16; type S = TLWE; let mut rng = rand::thread_rng(); for _ in 0..200 { let (sk, pk) = S::new_key(&mut rng)?; let msg_dist = Uniform::new(0_u64, T); let m = Rq::::rand_u64(&mut rng, msg_dist)?; dbg!(&m); let p: Tn<1> = S::encode::(m); dbg!(&p); let c = S::encrypt(&mut rng, &pk, &p)?; let p_recovered = c.decrypt(&sk); let m_recovered = S::decode::(p_recovered); assert_eq!(m, m_recovered); // same but using encrypt_s (with sk instead of pk)) let c = S::encrypt_s(&mut rng, &sk, &p)?; let p_recovered = c.decrypt(&sk); let m_recovered = S::decode::(p_recovered); assert_eq!(m, m_recovered); } Ok(()) } }