1use crate::B32;
2use crate::algebra::{
3 Ntt, NttInverse, NttMatrix, NttVector, Polynomial, Vector, matrix_sample_ntt, sample_poly_cbd,
4 sample_poly_vec_cbd,
5};
6use crate::compress::Compress;
7use crate::crypto::{G, PRF};
8use crate::param::{EncodedDecryptionKey, EncodedEncryptionKey, PkeParams};
9use array::typenum::{U1, Unsigned};
10use core::fmt;
11use kem::{Ciphertext, InvalidKey};
12use module_lattice::{
13 Encode,
14 ctutils::{Choice, CtEq},
15};
16
17#[cfg(feature = "zeroize")]
18use zeroize::Zeroize;
19
20#[derive(Clone, Default)]
23pub(crate) struct DecryptionKey<P>
24where
25 P: PkeParams,
26{
27 s_hat: NttVector<P::K>,
28}
29
30impl<P> fmt::Debug for DecryptionKey<P>
32where
33 P: PkeParams,
34{
35 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36 f.debug_struct("DecryptionKey").finish_non_exhaustive()
37 }
38}
39
40impl<P> CtEq for DecryptionKey<P>
41where
42 P: PkeParams,
43{
44 fn ct_eq(&self, other: &Self) -> Choice {
45 self.s_hat.ct_eq(&other.s_hat)
46 }
47}
48
49impl<P> Eq for DecryptionKey<P> where P: PkeParams {}
50impl<P> PartialEq for DecryptionKey<P>
51where
52 P: PkeParams,
53{
54 fn eq(&self, other: &Self) -> bool {
55 self.ct_eq(other).into()
57 }
58}
59
60#[cfg(feature = "zeroize")]
61impl<P> Zeroize for DecryptionKey<P>
62where
63 P: PkeParams,
64{
65 fn zeroize(&mut self) {
66 self.s_hat.zeroize();
67 }
68}
69
70impl<P> DecryptionKey<P>
71where
72 P: PkeParams,
73{
74 pub(crate) fn generate(d: &B32) -> (Self, EncryptionKey<P>) {
77 let k = P::K::U8;
79 let (rho, sigma) = G(&[&d[..], &[k]]);
80
81 let A_hat: NttMatrix<P::K> = matrix_sample_ntt(&rho, false);
83 let s: Vector<P::K> = sample_poly_vec_cbd::<P::Eta1, P::K>(&sigma, 0);
84 let e: Vector<P::K> = sample_poly_vec_cbd::<P::Eta1, P::K>(&sigma, P::K::U8);
85
86 let s_hat = s.ntt();
88 let e_hat = e.ntt();
89
90 let t_hat = &(&A_hat * &s_hat) + &e_hat;
92
93 let dk = DecryptionKey { s_hat };
95 let ek = EncryptionKey { t_hat, rho };
96 (dk, ek)
97 }
98
99 pub(crate) fn decrypt(&self, ciphertext: &Ciphertext<P>) -> B32 {
102 let (c1, c2) = P::split_ct(ciphertext);
103
104 let mut u: Vector<P::K> = Encode::<P::Du>::decode(c1);
105 u.decompress::<P::Du>();
106
107 let mut v: Polynomial = Encode::<P::Dv>::decode(c2);
108 v.decompress::<P::Dv>();
109
110 let u_hat = u.ntt();
111 let sTu = (&self.s_hat * &u_hat).ntt_inverse();
112 let mut w = &v - &sTu;
113 Encode::<U1>::encode(w.compress::<U1>())
114 }
115
116 pub(crate) fn to_bytes(&self) -> EncodedDecryptionKey<P> {
118 P::encode_u12(&self.s_hat)
119 }
120
121 pub(crate) fn from_bytes(enc: &EncodedDecryptionKey<P>) -> Self {
123 let s_hat = P::decode_u12(enc);
124 Self { s_hat }
125 }
126}
127
128#[derive(Clone, Default, Debug, Eq, PartialEq)]
131pub(crate) struct EncryptionKey<P>
132where
133 P: PkeParams,
134{
135 t_hat: NttVector<P::K>,
136 rho: B32,
137}
138
139impl<P> EncryptionKey<P>
140where
141 P: PkeParams,
142{
143 pub(crate) fn encrypt(&self, message: &B32, randomness: &B32) -> Ciphertext<P> {
146 let r = sample_poly_vec_cbd::<P::Eta1, P::K>(randomness, 0);
147 let e1 = sample_poly_vec_cbd::<P::Eta2, P::K>(randomness, P::K::U8);
148
149 let prf_output = PRF::<P::Eta2>(randomness, 2 * P::K::U8);
150 let e2: Polynomial = sample_poly_cbd::<P::Eta2>(&prf_output);
151
152 let A_hat_t: NttMatrix<P::K> = matrix_sample_ntt(&self.rho, true);
153 let r_hat: NttVector<P::K> = r.ntt();
154 let ATr: Vector<P::K> = (&A_hat_t * &r_hat).ntt_inverse();
155 let mut u = ATr + e1;
156
157 let mut mu: Polynomial = Encode::<U1>::decode(message);
158 mu.decompress::<U1>();
159
160 let tTr: Polynomial = (&self.t_hat * &r_hat).ntt_inverse();
161 let mut v = &(&tTr + &e2) + μ
162
163 let c1 = Encode::<P::Du>::encode(u.compress::<P::Du>());
164 let c2 = Encode::<P::Dv>::encode(v.compress::<P::Dv>());
165 P::concat_ct(c1, c2)
166 }
167
168 pub(crate) fn to_bytes(&self) -> EncodedEncryptionKey<P> {
170 let t_hat = P::encode_u12(&self.t_hat);
171 P::concat_ek(t_hat, self.rho.clone())
172 }
173
174 pub(crate) fn from_bytes(enc: &EncodedEncryptionKey<P>) -> Result<Self, InvalidKey> {
180 let (t_hat, rho) = P::split_ek(enc);
181 let t_hat = P::decode_u12(t_hat);
182 let ret = Self {
183 t_hat,
184 rho: rho.clone(),
185 };
186
187 if &ret.to_bytes() == enc {
214 Ok(ret)
215 } else {
216 Err(InvalidKey)
217 }
218 }
219}
220
221#[cfg(test)]
222mod test {
223 use super::*;
224 use crate::{MlKem512, MlKem768, MlKem1024};
225 use ::kem::Generate;
226 use getrandom::{SysRng, rand_core::UnwrapErr};
227
228 fn round_trip_test<P>()
229 where
230 P: PkeParams,
231 {
232 let mut rng = UnwrapErr(SysRng);
233 let d = B32::generate_from_rng(&mut rng);
234 let original = B32::default();
235 let randomness = B32::default();
236
237 let (dk, ek) = DecryptionKey::<P>::generate(&d);
238 let encrypted = ek.encrypt(&original, &randomness);
239 let decrypted = dk.decrypt(&encrypted);
240 assert_eq!(original, decrypted);
241 }
242
243 #[test]
244 fn round_trip() {
245 round_trip_test::<MlKem512>();
246 round_trip_test::<MlKem768>();
247 round_trip_test::<MlKem1024>();
248 }
249
250 fn codec_test<P>()
251 where
252 P: PkeParams,
253 {
254 let mut rng = UnwrapErr(SysRng);
255 let d = B32::generate_from_rng(&mut rng);
256 let (dk_original, ek_original) = DecryptionKey::<P>::generate(&d);
257
258 let dk_encoded = dk_original.to_bytes();
259 let dk_decoded = DecryptionKey::from_bytes(&dk_encoded);
260 assert_eq!(dk_original, dk_decoded);
261
262 let ek_encoded = ek_original.to_bytes();
263 let ek_decoded = EncryptionKey::from_bytes(&ek_encoded).unwrap();
264 assert_eq!(ek_original, ek_decoded);
265 }
266
267 #[test]
268 fn codec() {
269 codec_test::<MlKem512>();
270 codec_test::<MlKem768>();
271 codec_test::<MlKem1024>();
272 }
273
274 #[test]
275 fn reject_invalid_encryption_keys() {
276 let invalid_key = [0xFF; 1184];
279 assert!(EncryptionKey::<MlKem768>::from_bytes(&invalid_key.into()).is_err());
280 }
281
282 fn key_inequality_test<P>()
283 where
284 P: PkeParams,
285 {
286 let mut rng = UnwrapErr(SysRng);
287 let d1 = B32::generate_from_rng(&mut rng);
288 let d2 = B32::generate_from_rng(&mut rng);
289
290 let (dk1, _) = DecryptionKey::<P>::generate(&d1);
291 let (dk2, _) = DecryptionKey::<P>::generate(&d2);
292
293 assert_ne!(dk1, dk2);
295 }
296
297 #[test]
298 fn key_inequality() {
299 key_inequality_test::<MlKem512>();
300 key_inequality_test::<MlKem768>();
301 key_inequality_test::<MlKem1024>();
302 }
303}