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