poulpy/poulpy-core/src/decryption/lwe_ct.rs
poulpy-core/src/decryption/lwe_ct.rsRaw
1use poulpy_hal::{
2 api::{ScratchOwnedAlloc, ScratchOwnedBorrow, ZnNormalizeInplace},
3 layouts::{Backend, DataMut, DataRef, Module, ScratchOwned, ZnxView, ZnxViewMut},
4 oep::{ScratchOwnedAllocImpl, ScratchOwnedBorrowImpl},
5};
6
7use crate::layouts::{LWE, LWEInfos, LWEPlaintext, LWESecret, LWEToMut, LWEPlaintextToMut, LWESecretToRef};
8
9impl<DataSelf: DataRef + DataMut> LWE<DataSelf>
10{
11 pub fn decrypt<P, S, M, B>(&mut self, module: &M, pt: &mut P, sk: S)
12 where
13 P: LWEPlaintextToMut,
14 S: LWESecretToRef,
15 M: LWEDecrypt<B>,
16 B: Backend + ScratchOwnedAllocImpl<B> + ScratchOwnedBorrowImpl<B>,
17 {
18 module.lwe_decrypt(self, pt, sk);
19 }
20}
21
22pub trait LWEDecrypt<BE: Backend>
23where
24 Self: Sized + ZnNormalizeInplace<BE>
25{
26 fn lwe_decrypt<R, P, S>(&self, res: &mut R, pt: &mut P, sk: S)
27 where
28 R: LWEToMut,
29 P: LWEPlaintextToMut,
30 S: LWESecretToRef,
31 BE: Backend + ScratchOwnedAllocImpl<BE> + ScratchOwnedBorrowImpl<BE>,
32 {
33
34 let res: &mut LWE<&mut [u8]> = &mut res.to_mut();
35 let pt: &mut LWEPlaintext<&mut [u8]> = &mut pt.to_mut();
36 let sk: LWESecret<&[u8]> = sk.to_ref();
37
38 #[cfg(debug_assertions)]
39 {
40 assert_eq!(res.n(), sk.n());
41 }
42
43 (0..pt.size().min(res.size())).for_each(|i| {
44 pt.data.at_mut(0, i)[0] = res.data.at(0, i)[0]
45 + res.data.at(0, i)[1..]
46 .iter()
47 .zip(sk.data.at(0, 0))
48 .map(|(x, y)| x * y)
49 .sum::<i64>();
50 });
51 self.zn_normalize_inplace(
52 1,
53 res.base2k().into(),
54 &mut pt.data,
55 0,
56 ScratchOwned::alloc(size_of::<i64>()).borrow(),
57 );
58 pt.base2k = res.base2k();
59 pt.k = crate::layouts::TorusPrecision(res.k().0.min(pt.size() as u32 * res.base2k().0));
60 }
61}
62
63impl<BE: Backend> LWEDecrypt<BE> for Module<BE> where
64 Self: Sized + ZnNormalizeInplace<BE>
65{
66
67}