poulpy/core/src/encryption/glwe_to_lwe_ksk.rs
core/src/encryption/glwe_to_lwe_ksk.rsRaw
1use backend::hal::{
2 api::{
3 ScratchAvailable, SvpApplyInplace, SvpPPolAllocBytes, SvpPrepare, TakeScalarZnx, TakeVecZnx, TakeVecZnxDft,
4 VecZnxAddInplace, VecZnxAddNormal, VecZnxAddScalarInplace, VecZnxAutomorphismInplace, VecZnxBigNormalize,
5 VecZnxDftAllocBytes, VecZnxDftFromVecZnx, VecZnxDftToVecZnxBigConsume, VecZnxFillUniform, VecZnxNormalize,
6 VecZnxNormalizeInplace, VecZnxNormalizeTmpBytes, VecZnxSub, VecZnxSubABInplace, VecZnxSwithcDegree, ZnxView, ZnxViewMut,
7 ZnxZero,
8 },
9 layouts::{Backend, DataMut, DataRef, Module, Scratch},
10};
11use sampling::source::Source;
12
13use crate::{
14 TakeGLWESecret, TakeGLWESecretPrepared,
15 layouts::{GGLWESwitchingKey, GLWESecret, GLWEToLWESwitchingKey, LWESecret, prepared::GLWESecretPrepared},
16};
17
18impl GLWEToLWESwitchingKey<Vec<u8>> {
19 pub fn encrypt_sk_scratch_space<B: Backend>(module: &Module<B>, n: usize, basek: usize, k: usize, rank_in: usize) -> usize
20 where
21 Module<B>: SvpPPolAllocBytes + VecZnxNormalizeTmpBytes + VecZnxDftAllocBytes + VecZnxNormalizeTmpBytes,
22 {
23 GLWESecretPrepared::bytes_of(module, n, rank_in)
24 + (GGLWESwitchingKey::encrypt_sk_scratch_space(module, n, basek, k, rank_in, 1) | GLWESecret::bytes_of(n, rank_in))
25 }
26}
27
28impl<D: DataMut> GLWEToLWESwitchingKey<D> {
29 pub fn encrypt_sk<DLwe, DGlwe, B: Backend>(
30 &mut self,
31 module: &Module<B>,
32 sk_lwe: &LWESecret<DLwe>,
33 sk_glwe: &GLWESecret<DGlwe>,
34 source_xa: &mut Source,
35 source_xe: &mut Source,
36 sigma: f64,
37 scratch: &mut Scratch<B>,
38 ) where
39 DLwe: DataRef,
40 DGlwe: DataRef,
41 Module<B>: VecZnxAutomorphismInplace
42 + VecZnxAddScalarInplace
43 + VecZnxDftAllocBytes
44 + VecZnxBigNormalize<B>
45 + VecZnxDftFromVecZnx<B>
46 + SvpApplyInplace<B>
47 + VecZnxDftToVecZnxBigConsume<B>
48 + VecZnxNormalizeTmpBytes
49 + VecZnxFillUniform
50 + VecZnxSubABInplace
51 + VecZnxAddInplace
52 + VecZnxNormalizeInplace<B>
53 + VecZnxAddNormal
54 + VecZnxNormalize<B>
55 + VecZnxSub
56 + SvpPrepare<B>
57 + VecZnxSwithcDegree
58 + SvpPPolAllocBytes,
59 Scratch<B>: TakeVecZnxDft<B> + ScratchAvailable + TakeVecZnx + TakeScalarZnx + TakeGLWESecretPrepared<B>,
60 {
61 #[cfg(debug_assertions)]
62 {
63 assert!(sk_lwe.n() <= module.n());
64 }
65
66 let (mut sk_lwe_as_glwe, scratch1) = scratch.take_glwe_secret(sk_glwe.n(), 1);
67 sk_lwe_as_glwe.data.zero();
68 sk_lwe_as_glwe.data.at_mut(0, 0)[..sk_lwe.n()].copy_from_slice(sk_lwe.data.at(0, 0));
69 module.vec_znx_automorphism_inplace(-1, &mut sk_lwe_as_glwe.data.as_vec_znx_mut(), 0);
70
71 self.0.encrypt_sk(
72 module,
73 sk_glwe,
74 &sk_lwe_as_glwe,
75 source_xa,
76 source_xe,
77 sigma,
78 scratch1,
79 );
80 }
81}