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, ScalarZnxAlloc, ScratchOwnedAlloc, ScratchOwnedBorrow, SvpApplyInplace, SvpPPolAlloc, SvpPrepare,
  5            VecZnxAddNormal, VecZnxAlloc, VecZnxBigAddSmallInplace, VecZnxBigAlloc, VecZnxBigNormalize,
  6            VecZnxBigNormalizeTmpBytes, VecZnxBigSubSmallBInplace, VecZnxDecodeVeci64, VecZnxDftAlloc, VecZnxDftFromVecZnx,
  7            VecZnxDftToVecZnxBigTmpA, VecZnxEncodeVeci64, 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>> = module.scalar_znx_alloc(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(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>> = module.vec_znx_alloc(
 41        2,       // Number of columns
 42        ct_size, // Number of small poly per column
 43    );
 44
 45    // Fill the second column with random values: ct = (0, a)
 46    module.vec_znx_fill_uniform(basek, &mut ct, 1, ct_size * basek, &mut source);
 47
 48    let mut buf_dft: VecZnxDft<Vec<u8>, FFT64> = module.vec_znx_dft_alloc(1, ct_size);
 49
 50    module.vec_znx_dft_from_vec_znx(1, 0, &mut buf_dft, 0, &ct, 1);
 51
 52    // Applies DFT(ct[1]) * DFT(s)
 53    module.svp_apply_inplace(
 54        &mut buf_dft, // DFT(ct[1] * s)
 55        0,            // Selects the first column of res
 56        &s_dft,       // DFT(s)
 57        0,            // Selects the first column of s_dft
 58    );
 59
 60    // Alias scratch space (VecZnxDft<B> is always at least as big as VecZnxBig<B>)
 61
 62    // BIG(ct[1] * s) <- IDFT(DFT(ct[1] * s)) (not normalized)
 63    let mut buf_big: VecZnxBig<Vec<u8>, FFT64> = module.vec_znx_big_alloc(1, ct_size);
 64    module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut buf_big, 0, &mut buf_dft, 0);
 65
 66    // Creates a plaintext: VecZnx with 1 column
 67    let mut m = module.vec_znx_alloc(
 68        1,        // Number of columns
 69        msg_size, // Number of small polynomials
 70    );
 71    let mut want: Vec<i64> = vec![0; n];
 72    want.iter_mut()
 73        .for_each(|x| *x = source.next_u64n(16, 15) as i64);
 74    module.encode_vec_i64(basek, &mut m, 0, log_scale, &want, 4);
 75    module.vec_znx_normalize_inplace(basek, &mut m, 0, scratch.borrow());
 76
 77    // m - BIG(ct[1] * s)
 78    module.vec_znx_big_sub_small_b_inplace(
 79        &mut buf_big,
 80        0, // Selects the first column of the receiver
 81        &m,
 82        0, // Selects the first column of the message
 83    );
 84
 85    // Normalizes back to VecZnx
 86    // ct[0] <- m - BIG(c1 * s)
 87    module.vec_znx_big_normalize(
 88        basek,
 89        &mut ct,
 90        0, // Selects the first column of ct (ct[0])
 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        basek,
100        &mut ct,
101        0,               // Selects the first column of ct (ct[0])
102        basek * ct_size, // Scaling of the noise: 2^{-basek * 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_from_vec_znx(1, 0, &mut buf_dft, 0, &ct, 1);
114    module.svp_apply_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_dft_to_vec_znx_big_tmp_a(&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 = module.vec_znx_alloc(1, ct_size);
129    module.vec_znx_big_normalize(basek, &mut res, 0, &buf_big, 0, scratch.borrow());
130
131    // have = m * 2^{log_scale} + e
132    let mut have: Vec<i64> = vec![i64::default(); n];
133    module.decode_vec_i64(basek, &mut res, 0, ct_size * basek, &mut have);
134
135    let scale: f64 = (1 << (res.size() * basek - log_scale)) as f64;
136    izip!(want.iter(), have.iter())
137        .enumerate()
138        .for_each(|(i, (a, b))| {
139            println!("{}: {} {}", i, a, (*b as f64) / scale);
140        });
141}