poulpy/base2k/examples/rlwe_encrypt.rs
base2k/examples/rlwe_encrypt.rsRaw
1use base2k::{Module, Scalar, SvpPPol, VecZnx, VecZnxBig, VecZnxDft, FFT64};
2use itertools::izip;
3use sampling::source::Source;
4
5fn main() {
6 let n: usize = 16;
7 let log_base2k: usize = 18;
8 let limbs: usize = 3;
9 let log_scale: usize = (limbs - 1) * log_base2k - 5;
10 let module: Module = Module::new::<FFT64>(n);
11
12 let mut carry: Vec<u8> = vec![0; module.vec_znx_big_normalize_tmp_bytes()];
13
14 let seed: [u8; 32] = [0; 32];
15 let mut source: Source = Source::new(seed);
16
17 let mut res: VecZnx = VecZnx::new(n, log_base2k, limbs);
18
19 // s <- Z_{-1, 0, 1}[X]/(X^{N}+1)
20 let mut s: Scalar = Scalar::new(n);
21 s.fill_ternary_prob(0.5, &mut source);
22
23 // Buffer to store s in the DFT domain
24 let mut s_ppol: SvpPPol = module.svp_new_ppol();
25
26 // s_ppol <- DFT(s)
27 module.svp_prepare(&mut s_ppol, &s);
28
29 // a <- Z_{2^prec}[X]/(X^{N}+1)
30 let mut a: VecZnx = VecZnx::new(n, log_base2k, limbs);
31 a.fill_uniform(&mut source, log_base2k * limbs);
32
33 // Scratch space for DFT values
34 let mut buf_dft: VecZnxDft = module.new_vec_znx_dft(a.limbs());
35
36 // Applies buf_dft <- s * a
37 module.svp_apply_dft(&mut buf_dft, &s_ppol, &a);
38
39 // Alias scratch space
40 let mut buf_big: VecZnxBig = buf_dft.as_vec_znx_big();
41
42 // buf_big <- IDFT(buf_dft) (not normalized)
43 module.vec_znx_idft_tmp_a(&mut buf_big, &mut buf_dft, a.limbs());
44
45 let mut m: VecZnx = VecZnx::new(n, log_base2k, 2);
46
47 let mut want: Vec<i64> = vec![0; n];
48 want.iter_mut()
49 .for_each(|x| *x = source.next_u64n(16, 15) as i64);
50
51 // m
52 m.from_i64(&want, 4, log_scale);
53 m.normalize(&mut carry);
54
55 // buf_big <- m - buf_big
56 module.vec_znx_big_sub_small_a_inplace(&mut buf_big, &m);
57
58 // b <- normalize(buf_big) + e
59 let mut b: VecZnx = VecZnx::new(n, log_base2k, limbs);
60 module.vec_znx_big_normalize(&mut b, &buf_big, &mut carry);
61 b.add_normal(&mut source, 3.2, 19.0, log_base2k * limbs);
62
63 //Decrypt
64
65 // buf_big <- a * s
66 module.svp_apply_dft(&mut buf_dft, &s_ppol, &a);
67 module.vec_znx_idft_tmp_a(&mut buf_big, &mut buf_dft, b.limbs());
68
69 // buf_big <- a * s + b
70 module.vec_znx_big_add_small_inplace(&mut buf_big, &b);
71
72 // res <- normalize(buf_big)
73 module.vec_znx_big_normalize(&mut res, &buf_big, &mut carry);
74
75 // have = m * 2^{log_scale} + e
76 let mut have: Vec<i64> = vec![i64::default(); n];
77 res.to_i64(&mut have, res.limbs() * log_base2k);
78
79 let scale: f64 = (1 << (res.limbs() * log_base2k - log_scale)) as f64;
80 izip!(want.iter(), have.iter())
81 .enumerate()
82 .for_each(|(i, (a, b))| {
83 println!("{}: {} {}", i, a, (*b as f64) / scale);
84 })
85}