poulpy_core/decryption/
glwe_ct.rs

1use poulpy_hal::{
2    api::{
3        SvpApplyDftToDftInplace, TakeVecZnxBig, TakeVecZnxDft, VecZnxBigAddInplace, VecZnxBigAddSmallInplace, VecZnxBigNormalize,
4        VecZnxDftAllocBytes, VecZnxDftApply, VecZnxIdftApplyConsume, VecZnxNormalizeTmpBytes,
5    },
6    layouts::{Backend, DataMut, DataRef, DataViewMut, Module, Scratch},
7};
8
9use crate::layouts::{GLWECiphertext, GLWEPlaintext, Infos, prepared::GLWESecretPrepared};
10
11impl GLWECiphertext<Vec<u8>> {
12    pub fn decrypt_scratch_space<B: Backend>(module: &Module<B>, basek: usize, k: usize) -> usize
13    where
14        Module<B>: VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes,
15    {
16        let size: usize = k.div_ceil(basek);
17        (module.vec_znx_normalize_tmp_bytes() | module.vec_znx_dft_alloc_bytes(1, size)) + module.vec_znx_dft_alloc_bytes(1, size)
18    }
19}
20
21impl<DataSelf: DataRef> GLWECiphertext<DataSelf> {
22    pub fn decrypt<DataPt: DataMut, DataSk: DataRef, B: Backend>(
23        &self,
24        module: &Module<B>,
25        pt: &mut GLWEPlaintext<DataPt>,
26        sk: &GLWESecretPrepared<DataSk, B>,
27        scratch: &mut Scratch<B>,
28    ) where
29        Module<B>: VecZnxDftApply<B>
30            + SvpApplyDftToDftInplace<B>
31            + VecZnxIdftApplyConsume<B>
32            + VecZnxBigAddInplace<B>
33            + VecZnxBigAddSmallInplace<B>
34            + VecZnxBigNormalize<B>,
35        Scratch<B>: TakeVecZnxDft<B> + TakeVecZnxBig<B>,
36    {
37        #[cfg(debug_assertions)]
38        {
39            assert_eq!(self.rank(), sk.rank());
40            assert_eq!(self.n(), sk.n());
41            assert_eq!(pt.n(), sk.n());
42        }
43
44        let cols: usize = self.rank() + 1;
45
46        let (mut c0_big, scratch_1) = scratch.take_vec_znx_big(self.n(), 1, self.size()); // TODO optimize size when pt << ct
47        c0_big.data_mut().fill(0);
48
49        {
50            (1..cols).for_each(|i| {
51                // ci_dft = DFT(a[i]) * DFT(s[i])
52                let (mut ci_dft, _) = scratch_1.take_vec_znx_dft(self.n(), 1, self.size()); // TODO optimize size when pt << ct
53                module.vec_znx_dft_apply(1, 0, &mut ci_dft, 0, &self.data, i);
54                module.svp_apply_dft_to_dft_inplace(&mut ci_dft, 0, &sk.data, i - 1);
55                let ci_big = module.vec_znx_idft_apply_consume(ci_dft);
56
57                // c0_big += a[i] * s[i]
58                module.vec_znx_big_add_inplace(&mut c0_big, 0, &ci_big, 0);
59            });
60        }
61
62        // c0_big = (a * s) + (-a * s + m + e) = BIG(m + e)
63        module.vec_znx_big_add_small_inplace(&mut c0_big, 0, &self.data, 0);
64
65        // pt = norm(BIG(m + e))
66        module.vec_znx_big_normalize(self.basek(), &mut pt.data, 0, &c0_big, 0, scratch_1);
67
68        pt.basek = self.basek();
69        pt.k = pt.k().min(self.k());
70    }
71}