arnaucube
arnaucube/poulpyPublic Self-hosted repository
poulpy/core/src/glwe/encryption.rs
core/src/glwe/encryption.rsRaw
  1use backend::{
  2    AddNormal, FFT64, FillUniform, Module, ScalarZnxAlloc, ScalarZnxDftAlloc, ScalarZnxDftOps, Scratch, VecZnxAlloc, VecZnxBig,
  3    VecZnxBigAlloc, VecZnxBigOps, VecZnxBigScratch, VecZnxDftAlloc, VecZnxDftOps, VecZnxOps, ZnxZero,
  4};
  5use sampling::source::Source;
  6
  7use crate::{FourierGLWESecret, GLWECiphertext, GLWEPlaintext, GLWEPublicKey, Infos, SIX_SIGMA, dist::Distribution};
  8
  9impl GLWECiphertext<Vec<u8>> {
 10    pub fn encrypt_sk_scratch_space(module: &Module<FFT64>, basek: usize, k: usize) -> usize {
 11        let size: usize = k.div_ceil(basek);
 12        module.vec_znx_big_normalize_tmp_bytes() + module.bytes_of_vec_znx_dft(1, size) + module.bytes_of_vec_znx(1, size)
 13    }
 14    pub fn encrypt_pk_scratch_space(module: &Module<FFT64>, basek: usize, k: usize) -> usize {
 15        let size: usize = k.div_ceil(basek);
 16        ((module.bytes_of_vec_znx_dft(1, size) + module.bytes_of_vec_znx_big(1, size)) | module.bytes_of_scalar_znx(1))
 17            + module.bytes_of_scalar_znx_dft(1)
 18            + module.vec_znx_big_normalize_tmp_bytes()
 19    }
 20}
 21
 22impl<DataSelf: AsRef<[u8]> + AsMut<[u8]>> GLWECiphertext<DataSelf> {
 23    pub fn encrypt_sk<DataPt: AsRef<[u8]>, DataSk: AsRef<[u8]>>(
 24        &mut self,
 25        module: &Module<FFT64>,
 26        pt: &GLWEPlaintext<DataPt>,
 27        sk: &FourierGLWESecret<DataSk, FFT64>,
 28        source_xa: &mut Source,
 29        source_xe: &mut Source,
 30        sigma: f64,
 31        scratch: &mut Scratch,
 32    ) {
 33        self.encrypt_sk_private(
 34            module,
 35            Some((pt, 0)),
 36            sk,
 37            source_xa,
 38            source_xe,
 39            sigma,
 40            scratch,
 41        );
 42    }
 43
 44    pub fn encrypt_zero_sk<DataSk: AsRef<[u8]>>(
 45        &mut self,
 46        module: &Module<FFT64>,
 47        sk: &FourierGLWESecret<DataSk, FFT64>,
 48        source_xa: &mut Source,
 49        source_xe: &mut Source,
 50        sigma: f64,
 51        scratch: &mut Scratch,
 52    ) {
 53        self.encrypt_sk_private(
 54            module,
 55            None::<(&GLWEPlaintext<Vec<u8>>, usize)>,
 56            sk,
 57            source_xa,
 58            source_xe,
 59            sigma,
 60            scratch,
 61        );
 62    }
 63
 64    pub fn encrypt_pk<DataPt: AsRef<[u8]>, DataPk: AsRef<[u8]>>(
 65        &mut self,
 66        module: &Module<FFT64>,
 67        pt: &GLWEPlaintext<DataPt>,
 68        pk: &GLWEPublicKey<DataPk, FFT64>,
 69        source_xu: &mut Source,
 70        source_xe: &mut Source,
 71        sigma: f64,
 72        scratch: &mut Scratch,
 73    ) {
 74        self.encrypt_pk_private::<DataPt, DataPk>(
 75            module,
 76            Some((pt, 0)),
 77            pk,
 78            source_xu,
 79            source_xe,
 80            sigma,
 81            scratch,
 82        );
 83    }
 84
 85    pub fn encrypt_zero_pk<DataPk: AsRef<[u8]>>(
 86        &mut self,
 87        module: &Module<FFT64>,
 88        pk: &GLWEPublicKey<DataPk, FFT64>,
 89        source_xu: &mut Source,
 90        source_xe: &mut Source,
 91        sigma: f64,
 92        scratch: &mut Scratch,
 93    ) {
 94        self.encrypt_pk_private::<Vec<u8>, DataPk>(
 95            module,
 96            None::<(&GLWEPlaintext<Vec<u8>>, usize)>,
 97            pk,
 98            source_xu,
 99            source_xe,
100            sigma,
101            scratch,
102        );
103    }
104
105    pub(crate) fn encrypt_sk_private<DataPt: AsRef<[u8]>, DataSk: AsRef<[u8]>>(
106        &mut self,
107        module: &Module<FFT64>,
108        pt: Option<(&GLWEPlaintext<DataPt>, usize)>,
109        sk: &FourierGLWESecret<DataSk, FFT64>,
110        source_xa: &mut Source,
111        source_xe: &mut Source,
112        sigma: f64,
113        scratch: &mut Scratch,
114    ) {
115        #[cfg(debug_assertions)]
116        {
117            assert_eq!(self.rank(), sk.rank());
118            assert_eq!(sk.n(), module.n());
119            assert_eq!(self.n(), module.n());
120            if let Some((pt, col)) = pt {
121                assert_eq!(pt.n(), module.n());
122                assert!(col < self.rank() + 1);
123            }
124            assert!(
125                scratch.available() >= GLWECiphertext::encrypt_sk_scratch_space(module, self.basek(), self.k()),
126                "scratch.available(): {} < GLWECiphertext::encrypt_sk_scratch_space: {}",
127                scratch.available(),
128                GLWECiphertext::encrypt_sk_scratch_space(module, self.basek(), self.k())
129            )
130        }
131
132        let basek: usize = self.basek();
133        let k: usize = self.k();
134        let size: usize = self.size();
135        let cols: usize = self.rank() + 1;
136
137        let (mut c0_big, scratch_1) = scratch.tmp_vec_znx(module, 1, size);
138        c0_big.zero();
139
140        {
141            // c[i] = uniform
142            // c[0] -= c[i] * s[i],
143            (1..cols).for_each(|i| {
144                let (mut ci_dft, scratch_2) = scratch_1.tmp_vec_znx_dft(module, 1, size);
145
146                // c[i] = uniform
147                self.data.fill_uniform(basek, i, size, source_xa);
148
149                // c[i] = norm(IDFT(DFT(c[i]) * DFT(s[i])))
150                module.vec_znx_dft(1, 0, &mut ci_dft, 0, &self.data, i);
151                module.svp_apply_inplace(&mut ci_dft, 0, &sk.data, i - 1);
152                let ci_big: VecZnxBig<&mut [u8], FFT64> = module.vec_znx_idft_consume(ci_dft);
153
154                // use c[0] as buffer, which is overwritten later by the normalization step
155                module.vec_znx_big_normalize(basek, &mut self.data, 0, &ci_big, 0, scratch_2);
156
157                // c0_tmp = -c[i] * s[i] (use c[0] as buffer)
158                module.vec_znx_sub_ab_inplace(&mut c0_big, 0, &self.data, 0);
159
160                // c[i] += m if col = i
161                if let Some((pt, col)) = pt {
162                    if i == col {
163                        module.vec_znx_add_inplace(&mut self.data, i, &pt.data, 0);
164                        module.vec_znx_normalize_inplace(basek, &mut self.data, i, scratch_2);
165                    }
166                }
167            });
168        }
169
170        // c[0] += e
171        c0_big.add_normal(basek, 0, k, source_xe, sigma, sigma * SIX_SIGMA);
172
173        // c[0] += m if col = 0
174        if let Some((pt, col)) = pt {
175            if col == 0 {
176                module.vec_znx_add_inplace(&mut c0_big, 0, &pt.data, 0);
177            }
178        }
179
180        // c[0] = norm(c[0])
181        module.vec_znx_normalize(basek, &mut self.data, 0, &c0_big, 0, scratch_1);
182    }
183
184    pub(crate) fn encrypt_pk_private<DataPt: AsRef<[u8]>, DataPk: AsRef<[u8]>>(
185        &mut self,
186        module: &Module<FFT64>,
187        pt: Option<(&GLWEPlaintext<DataPt>, usize)>,
188        pk: &GLWEPublicKey<DataPk, FFT64>,
189        source_xu: &mut Source,
190        source_xe: &mut Source,
191        sigma: f64,
192        scratch: &mut Scratch,
193    ) {
194        #[cfg(debug_assertions)]
195        {
196            assert_eq!(self.basek(), pk.basek());
197            assert_eq!(self.n(), module.n());
198            assert_eq!(pk.n(), module.n());
199            assert_eq!(self.rank(), pk.rank());
200            if let Some((pt, _)) = pt {
201                assert_eq!(pt.basek(), pk.basek());
202                assert_eq!(pt.n(), module.n());
203            }
204        }
205
206        let basek: usize = pk.basek();
207        let size_pk: usize = pk.size();
208        let cols: usize = self.rank() + 1;
209
210        // Generates u according to the underlying secret distribution.
211        let (mut u_dft, scratch_1) = scratch.tmp_scalar_znx_dft(module, 1);
212
213        {
214            let (mut u, _) = scratch_1.tmp_scalar_znx(module, 1);
215            match pk.dist {
216                Distribution::NONE => panic!(
217                    "invalid public key: SecretDistribution::NONE, ensure it has been correctly intialized through \
218                     Self::generate"
219                ),
220                Distribution::TernaryFixed(hw) => u.fill_ternary_hw(0, hw, source_xu),
221                Distribution::TernaryProb(prob) => u.fill_ternary_prob(0, prob, source_xu),
222                Distribution::BinaryFixed(hw) => u.fill_binary_hw(0, hw, source_xu),
223                Distribution::BinaryProb(prob) => u.fill_binary_prob(0, prob, source_xu),
224                Distribution::BinaryBlock(block_size) => u.fill_binary_block(0, block_size, source_xu),
225                Distribution::ZERO => {}
226            }
227
228            module.svp_prepare(&mut u_dft, 0, &u, 0);
229        }
230
231        // ct[i] = pk[i] * u + ei (+ m if col = i)
232        (0..cols).for_each(|i| {
233            let (mut ci_dft, scratch_2) = scratch_1.tmp_vec_znx_dft(module, 1, size_pk);
234            // ci_dft = DFT(u) * DFT(pk[i])
235            module.svp_apply(&mut ci_dft, 0, &u_dft, 0, &pk.data.data, i);
236
237            // ci_big = u * p[i]
238            let mut ci_big = module.vec_znx_idft_consume(ci_dft);
239
240            // ci_big = u * pk[i] + e
241            ci_big.add_normal(basek, 0, pk.k(), source_xe, sigma, sigma * SIX_SIGMA);
242
243            // ci_big = u * pk[i] + e + m (if col = i)
244            if let Some((pt, col)) = pt {
245                if col == i {
246                    module.vec_znx_big_add_small_inplace(&mut ci_big, 0, &pt.data, 0);
247                }
248            }
249
250            // ct[i] = norm(ci_big)
251            module.vec_znx_big_normalize(basek, &mut self.data, i, &ci_big, 0, scratch_2);
252        });
253    }
254}