arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/backend/examples/rlwe_encrypt.rs
backend/examples/rlwe_encrypt.rsRaw
  1use backend::{
  2    hal::{
  3        api::{
  4            ModuleNew, ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, SvpPPolAlloc, SvpPrepare, VecZnxAddNormal,
  5            VecZnxBigAddSmallInplace, VecZnxBigAlloc, VecZnxBigNormalize, VecZnxBigNormalizeTmpBytes, VecZnxBigSubSmallBInplace,
  6            VecZnxDecodeVeci64, VecZnxDftAlloc, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigTmpA, VecZnxEncodeVeci64,
  7            VecZnxFillUniform, VecZnxNormalizeInplace, ZnxInfos,
  8        },
  9        layouts::{Module, ScalarZnx, ScratchOwned, SvpPPol, VecZnx, VecZnxBig, VecZnxDft},
 10    },
 11    implementation::cpu_spqlios::FFT64,
 12};
 13use itertools::izip;
 14use sampling::source::Source;
 15
 16fn main() {
 17    let n: usize = 16;
 18    let basek: usize = 18;
 19    let ct_size: usize = 3;
 20    let msg_size: usize = 2;
 21    let log_scale: usize = msg_size * basek - 5;
 22    let module: Module<FFT64> = Module::<FFT64>::new(n as u64);
 23
 24    let mut scratch: ScratchOwned<FFT64> = ScratchOwned::<FFT64>::alloc(module.vec_znx_big_normalize_tmp_bytes(n));
 25
 26    let seed: [u8; 32] = [0; 32];
 27    let mut source: Source = Source::new(seed);
 28
 29    // s <- Z_{-1, 0, 1}[X]/(X^{N}+1)
 30    let mut s: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(module.n(), 1);
 31    s.fill_ternary_prob(0, 0.5, &mut source);
 32
 33    // Buffer to store s in the DFT domain
 34    let mut s_dft: SvpPPol<Vec<u8>, FFT64> = module.svp_ppol_alloc(n, s.cols());
 35
 36    // s_dft <- DFT(s)
 37    module.svp_prepare(&mut s_dft, 0, &s, 0);
 38
 39    // Allocates a VecZnx with two columns: ct=(0, 0)
 40    let mut ct: VecZnx<Vec<u8>> = VecZnx::alloc(
 41        module.n(),
 42        2,       // Number of columns
 43        ct_size, // Number of small poly per column
 44    );
 45
 46    // Fill the second column with random values: ct = (0, a)
 47    module.vec_znx_fill_uniform(basek, &mut ct, 1, ct_size * basek, &mut source);
 48
 49    let mut buf_dft: VecZnxDft<Vec<u8>, FFT64> = module.vec_znx_dft_alloc(n, 1, ct_size);
 50
 51    module.vec_znx_dft_from_vec_znx(1, 0, &mut buf_dft, 0, &ct, 1);
 52
 53    // Applies DFT(ct[1]) * DFT(s)
 54    module.svp_apply_inplace(
 55        &mut buf_dft, // DFT(ct[1] * s)
 56        0,            // Selects the first column of res
 57        &s_dft,       // DFT(s)
 58        0,            // Selects the first column of s_dft
 59    );
 60
 61    // Alias scratch space (VecZnxDft<B> is always at least as big as VecZnxBig<B>)
 62
 63    // BIG(ct[1] * s) <- IDFT(DFT(ct[1] * s)) (not normalized)
 64    let mut buf_big: VecZnxBig<Vec<u8>, FFT64> = module.vec_znx_big_alloc(n, 1, ct_size);
 65    module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut buf_big, 0, &mut buf_dft, 0);
 66
 67    // Creates a plaintext: VecZnx with 1 column
 68    let mut m = VecZnx::alloc(
 69        module.n(),
 70        1,        // Number of columns
 71        msg_size, // Number of small polynomials
 72    );
 73    let mut want: Vec<i64> = vec![0; n];
 74    want.iter_mut()
 75        .for_each(|x| *x = source.next_u64n(16, 15) as i64);
 76    module.encode_vec_i64(basek, &mut m, 0, log_scale, &want, 4);
 77    module.vec_znx_normalize_inplace(basek, &mut m, 0, scratch.borrow());
 78
 79    // m - BIG(ct[1] * s)
 80    module.vec_znx_big_sub_small_b_inplace(
 81        &mut buf_big,
 82        0, // Selects the first column of the receiver
 83        &m,
 84        0, // Selects the first column of the message
 85    );
 86
 87    // Normalizes back to VecZnx
 88    // ct[0] <- m - BIG(c1 * s)
 89    module.vec_znx_big_normalize(
 90        basek,
 91        &mut ct,
 92        0, // Selects the first column of ct (ct[0])
 93        &buf_big,
 94        0, // Selects the first column of buf_big
 95        scratch.borrow(),
 96    );
 97
 98    // Add noise to ct[0]
 99    // ct[0] <- ct[0] + e
100    module.vec_znx_add_normal(
101        basek,
102        &mut ct,
103        0,               // Selects the first column of ct (ct[0])
104        basek * ct_size, // Scaling of the noise: 2^{-basek * limbs}
105        &mut source,
106        3.2,       // Standard deviation
107        3.2 * 6.0, // Truncatation bound
108    );
109
110    // Final ciphertext: ct = (-a * s + m + e, a)
111
112    // Decryption
113
114    // DFT(ct[1] * s)
115    module.vec_znx_dft_from_vec_znx(1, 0, &mut buf_dft, 0, &ct, 1);
116    module.svp_apply_inplace(
117        &mut buf_dft,
118        0, // Selects the first column of res.
119        &s_dft,
120        0,
121    );
122
123    // BIG(c1 * s) = IDFT(DFT(c1 * s))
124    module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut buf_big, 0, &mut buf_dft, 0);
125
126    // BIG(c1 * s) + ct[0]
127    module.vec_znx_big_add_small_inplace(&mut buf_big, 0, &ct, 0);
128
129    // m + e <- BIG(ct[1] * s + ct[0])
130    let mut res = VecZnx::alloc(module.n(), 1, ct_size);
131    module.vec_znx_big_normalize(basek, &mut res, 0, &buf_big, 0, scratch.borrow());
132
133    // have = m * 2^{log_scale} + e
134    let mut have: Vec<i64> = vec![i64::default(); n];
135    module.decode_vec_i64(basek, &mut res, 0, ct_size * basek, &mut have);
136
137    let scale: f64 = (1 << (res.size() * basek - log_scale)) as f64;
138    izip!(want.iter(), have.iter())
139        .enumerate()
140        .for_each(|(i, (a, b))| {
141            println!("{}: {} {}", i, a, (*b as f64) / scale);
142        });
143}