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            VecZnxDftAlloc, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigTmpA, VecZnxFillUniform, VecZnxNormalizeInplace, ZnxInfos,
  7        },
  8        layouts::{Module, ScalarZnx, ScratchOwned, SvpPPol, VecZnx, VecZnxBig, VecZnxDft},
  9    },
 10    implementation::cpu_spqlios::FFT64,
 11};
 12use itertools::izip;
 13use sampling::source::Source;
 14
 15fn main() {
 16    let n: usize = 16;
 17    let basek: usize = 18;
 18    let ct_size: usize = 3;
 19    let msg_size: usize = 2;
 20    let log_scale: usize = msg_size * basek - 5;
 21    let module: Module<FFT64> = Module::<FFT64>::new(n as u64);
 22
 23    let mut scratch: ScratchOwned<FFT64> = ScratchOwned::<FFT64>::alloc(module.vec_znx_big_normalize_tmp_bytes(n));
 24
 25    let seed: [u8; 32] = [0; 32];
 26    let mut source: Source = Source::new(seed);
 27
 28    // s <- Z_{-1, 0, 1}[X]/(X^{N}+1)
 29    let mut s: ScalarZnx<Vec<u8>> = ScalarZnx::alloc(module.n(), 1);
 30    s.fill_ternary_prob(0, 0.5, &mut source);
 31
 32    // Buffer to store s in the DFT domain
 33    let mut s_dft: SvpPPol<Vec<u8>, FFT64> = module.svp_ppol_alloc(n, s.cols());
 34
 35    // s_dft <- DFT(s)
 36    module.svp_prepare(&mut s_dft, 0, &s, 0);
 37
 38    // Allocates a VecZnx with two columns: ct=(0, 0)
 39    let mut ct: VecZnx<Vec<u8>> = VecZnx::alloc(
 40        module.n(),
 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(n, 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(n, 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 = VecZnx::alloc(
 68        module.n(),
 69        1,        // Number of columns
 70        msg_size, // Number of small polynomials
 71    );
 72    let mut want: Vec<i64> = vec![0; n];
 73    want.iter_mut()
 74        .for_each(|x| *x = source.next_u64n(16, 15) as i64);
 75    m.encode_vec_i64(basek, 0, log_scale, &want, 4);
 76    module.vec_znx_normalize_inplace(basek, &mut m, 0, scratch.borrow());
 77
 78    // m - BIG(ct[1] * s)
 79    module.vec_znx_big_sub_small_b_inplace(
 80        &mut buf_big,
 81        0, // Selects the first column of the receiver
 82        &m,
 83        0, // Selects the first column of the message
 84    );
 85
 86    // Normalizes back to VecZnx
 87    // ct[0] <- m - BIG(c1 * s)
 88    module.vec_znx_big_normalize(
 89        basek,
 90        &mut ct,
 91        0, // Selects the first column of ct (ct[0])
 92        &buf_big,
 93        0, // Selects the first column of buf_big
 94        scratch.borrow(),
 95    );
 96
 97    // Add noise to ct[0]
 98    // ct[0] <- ct[0] + e
 99    module.vec_znx_add_normal(
100        basek,
101        &mut ct,
102        0,               // Selects the first column of ct (ct[0])
103        basek * ct_size, // Scaling of the noise: 2^{-basek * limbs}
104        &mut source,
105        3.2,       // Standard deviation
106        3.2 * 6.0, // Truncatation bound
107    );
108
109    // Final ciphertext: ct = (-a * s + m + e, a)
110
111    // Decryption
112
113    // DFT(ct[1] * s)
114    module.vec_znx_dft_from_vec_znx(1, 0, &mut buf_dft, 0, &ct, 1);
115    module.svp_apply_inplace(
116        &mut buf_dft,
117        0, // Selects the first column of res.
118        &s_dft,
119        0,
120    );
121
122    // BIG(c1 * s) = IDFT(DFT(c1 * s))
123    module.vec_znx_dft_to_vec_znx_big_tmp_a(&mut buf_big, 0, &mut buf_dft, 0);
124
125    // BIG(c1 * s) + ct[0]
126    module.vec_znx_big_add_small_inplace(&mut buf_big, 0, &ct, 0);
127
128    // m + e <- BIG(ct[1] * s + ct[0])
129    let mut res = VecZnx::alloc(module.n(), 1, ct_size);
130    module.vec_znx_big_normalize(basek, &mut res, 0, &buf_big, 0, scratch.borrow());
131
132    // have = m * 2^{log_scale} + e
133    let mut have: Vec<i64> = vec![i64::default(); n];
134    res.decode_vec_i64(basek, 0, ct_size * basek, &mut have);
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}