Skip to main content

ml_kem/
pke.rs

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/// A `DecryptionKey` provides the ability to generate a new key pair, and decrypt an
21/// encrypted value.
22#[derive(Clone, Default)]
23pub(crate) struct DecryptionKey<P>
24where
25    P: PkeParams,
26{
27    s_hat: NttVector<P::K>,
28}
29
30// Don't print the secret vector `s_hat`
31impl<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        // Compare decryption keys in constant-time
56        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    /// Generate a new random decryption key according to the `K-PKE.KeyGen` procedure.
75    // Algorithm 12. K-PKE.KeyGen()
76    pub(crate) fn generate(d: &B32) -> (Self, EncryptionKey<P>) {
77        // Generate random seeds
78        let k = P::K::U8;
79        let (rho, sigma) = G(&[&d[..], &[k]]);
80
81        // Sample pseudo-random matrix and vectors
82        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        // NTT the vectors
87        let s_hat = s.ntt();
88        let e_hat = e.ntt();
89
90        // Compute the public value
91        let t_hat = &(&A_hat * &s_hat) + &e_hat;
92
93        // Assemble the keys
94        let dk = DecryptionKey { s_hat };
95        let ek = EncryptionKey { t_hat, rho };
96        (dk, ek)
97    }
98
99    /// Decrypt ciphertext to obtain the encrypted value, according to the K-PKE.Decrypt procedure.
100    // Algorithm 14. kK-PKE.Decrypt(dk_PKE, c)
101    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    /// Represent this decryption key as a byte array `(s_hat)`
117    pub(crate) fn to_bytes(&self) -> EncodedDecryptionKey<P> {
118        P::encode_u12(&self.s_hat)
119    }
120
121    /// Parse an decryption key from a byte array `(s_hat)`
122    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/// An `EncryptionKey` provides the ability to encrypt a value so that it can only be
129/// decrypted by the holder of the corresponding decapsulation key.
130#[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    /// Encrypt the specified message for the holder of the corresponding decryption key, using the
144    /// provided randomness, according the `K-PKE.Encrypt` procedure.
145    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) + &mu;
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    /// Represent this encryption key as a byte array `(t_hat || rho)`
169    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    /// Parse an encryption key from a byte array `(t_hat || rho)`.
175    ///
176    /// # Errors
177    /// Returns [`InvalidKey`] in the event that the key fails the encapsulation key checks
178    /// specified in FIPS 203 §7.2.
179    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        // Check the candidate encapsulation key is valid using the method specified in FIPS 203
188        // §7.2 ML-KEM Encapsulation:
189        //
190        // > Encapsulation key check. To check a candidate encapsulation key `ek`, perform the
191        // > following:
192        // >
193        // > 1. (Type check) If `ek` is not an array of bytes of length 384𝑘+32 for the value of 𝑘
194        // >    specified by the relevant parameter set, then input checking failed.
195        // > 2. (Modulus check) Perform the computation:
196        // >
197        // >    test ← ByteEncode₁₂(ByteDecode₁₂(ek[0:384𝑘]))
198        // >
199        // >    (see Section 4.2.1). If `test ≠ ek[0∶384𝑘]`, then input checking failed. This
200        // >    check ensures that the integers encoded in the public key are in the valid range
201        // >    `[0,q-1]`.
202        // >
203        // > If both checks pass, then `ML-KEM.Encaps` can be run with input `ek`. It is important
204        // > to note that this checking process does not guarantee that ek is a properly produced
205        // > output of `ML-KEM.KeyGen`.
206        // >
207        // > `ML-KEM.Encaps` shall not be run with an encapsulation key that has not been checked as
208        // > above.
209        //
210        // #1 is performed by the `EncodedEncryptionKey` type, and the following check vicariously
211        // performs #2 by encoding the integer-mod-q array using our implementation of ByteEncode₁₂
212        // and comparing the resulting serialization to see if it round-trips.
213        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        // Create an invalid key: all bytes set to 0xFF
277        // When decoded as 12-bit coefficients, this produces values of 0xFFF = 4095 > 3329
278        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        // Verify inequality (catches PartialEq mutation that returns true unconditionally)
294        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}