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