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