Skip to main content

ml_kem/
decapsulation_key.rs

1use crate::{
2    B32, EncapsulationKey, Seed, SharedKey,
3    crypto::{G, J},
4    param::{DecapsulationKeySize, ExpandedDecapsulationKey, KemParams},
5    pke::{DecryptionKey, EncryptionKey},
6};
7use array::{
8    Array, ArraySize,
9    sizes::{U32, U64},
10};
11use core::fmt;
12use kem::{
13    Ciphertext, Decapsulate, Decapsulator, Generate, InvalidKey, Kem, KeyExport, KeyInit,
14    KeySizeUser,
15};
16use module_lattice::{
17    MaybeBox,
18    ctutils::{Choice, CtEq, CtSelect},
19};
20use rand_core::{TryCryptoRng, TryRng};
21
22#[cfg(feature = "zeroize")]
23use zeroize::{Zeroize, ZeroizeOnDrop};
24
25/// A `DecapsulationKey` provides the ability to generate a new key pair, and decapsulate an
26/// encapsulated shared key.
27#[derive(Clone)]
28pub struct DecapsulationKey<P>
29where
30    P: KemParams,
31{
32    /// Decryption key.
33    dk_pke: MaybeBox<DecryptionKey<P>>,
34
35    /// Associated encapsulation key.
36    ek: EncapsulationKey<P>,
37
38    /// Seed this key was initialized from.
39    d: Option<MaybeBox<B32>>,
40
41    /// Random string used during the implicit rejection process.
42    z: MaybeBox<B32>,
43}
44
45impl<P> DecapsulationKey<P>
46where
47    P: KemParams,
48{
49    /// Create a [`DecapsulationKey`] instance from a 64-byte random seed value.
50    #[inline]
51    #[must_use]
52    pub fn from_seed(seed: Seed) -> Self {
53        let (d, z) = seed.split();
54        Self::generate_deterministic(d, z)
55    }
56
57    /// Initialize a [`DecapsulationKey`] from the serialized expanded key form.
58    ///
59    /// Note that this form is deprecated in practice; use [`DecapsulationKey::from_seed`].
60    /// See [`ExpandedKeyEncoding`] for more information.
61    ///
62    /// # Errors
63    /// - Returns [`InvalidKey`] in the event the expanded key failed validation
64    #[deprecated(since = "0.3.0", note = "use `DecapsulationKey::from_seed` instead")]
65    pub fn from_expanded(enc: &ExpandedDecapsulationKey<P>) -> Result<Self, InvalidKey> {
66        let (dk_pke, ek_pke, h, z) = P::split_dk(enc);
67        let ek_pke = EncryptionKey::from_bytes(ek_pke)?;
68
69        let ek = EncapsulationKey::from_encryption_key(ek_pke);
70        if ek.h() != *h {
71            return Err(InvalidKey);
72        }
73
74        let dk_pke = MaybeBox::new(DecryptionKey::from_bytes(dk_pke));
75
76        Ok(Self {
77            dk_pke,
78            ek,
79            d: None,
80            z: MaybeBox::new(z.clone()),
81        })
82    }
83
84    /// Serialize the [`Seed`] value: 64-bytes which can be used to reconstruct the
85    /// [`DecapsulationKey`].
86    ///
87    /// <div class="warning">
88    /// <b>Warning!</B>
89    ///
90    /// This value is key material. Please treat it with care.
91    /// </div>
92    ///
93    /// # Returns
94    /// - `Some` if the [`DecapsulationKey`] was initialized using `from_seed` or `generate`.
95    /// - `None` if the [`DecapsulationKey`] was initialized from the expanded form.
96    #[inline]
97    #[must_use]
98    pub fn to_seed(&self) -> Option<Seed> {
99        self.d.as_ref().map(|d| d.concat(*self.z))
100    }
101
102    /// Get the [`EncapsulationKey`] which corresponds to this [`DecapsulationKey`].
103    #[must_use]
104    pub fn encapsulation_key(&self) -> &EncapsulationKey<P> {
105        &self.ek
106    }
107
108    #[inline]
109    pub(crate) fn try_generate_from_rng<R>(rng: &mut R) -> Result<Self, <R as TryRng>::Error>
110    where
111        R: TryCryptoRng + ?Sized,
112    {
113        let d = B32::try_generate_from_rng(rng)?;
114        let z = B32::try_generate_from_rng(rng)?;
115        Ok(Self::generate_deterministic(d, z))
116    }
117
118    #[inline]
119    #[must_use]
120    #[allow(clippy::similar_names)] // allow dk_pke, ek_pke, following the spec
121    pub(crate) fn generate_deterministic(d: B32, z: B32) -> Self {
122        let (dk_pke, ek_pke) = DecryptionKey::generate(&d);
123        let ek = EncapsulationKey::from_encryption_key(ek_pke);
124
125        let dk_pke = MaybeBox::new(dk_pke);
126        let d = Some(MaybeBox::new(d));
127        let z = MaybeBox::new(z);
128
129        Self { dk_pke, ek, d, z }
130    }
131}
132
133// Only show the public encapsulation key so secrets don't end up in logs
134impl<P> fmt::Debug for DecapsulationKey<P>
135where
136    P: KemParams,
137{
138    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
139        f.debug_struct("DecapsulationKey")
140            .field("ek", &self.ek)
141            .finish_non_exhaustive()
142    }
143}
144
145// Handwritten to omit `d` in the comparisons, so keys initialized from seeds compare equally to
146// keys initialized from the expanded form
147impl<P> PartialEq for DecapsulationKey<P>
148where
149    P: KemParams,
150{
151    fn eq(&self, other: &Self) -> bool {
152        // Only the public encapsulation key may be compared in variable time.
153        let ek_eq = Choice::from_u8_lsb(u8::from(self.ek.eq(&other.ek)));
154        (self.dk_pke.ct_eq(&other.dk_pke) & ek_eq & self.z.ct_eq(&other.z)).into()
155    }
156}
157
158#[cfg(feature = "zeroize")]
159impl<P> Drop for DecapsulationKey<P>
160where
161    P: KemParams,
162{
163    fn drop(&mut self) {
164        self.dk_pke.zeroize();
165        if let Some(d) = self.d.as_mut() {
166            d.zeroize();
167        }
168        self.z.zeroize();
169    }
170}
171
172#[cfg(feature = "zeroize")]
173impl<P> ZeroizeOnDrop for DecapsulationKey<P> where P: KemParams {}
174
175impl<P> From<Seed> for DecapsulationKey<P>
176where
177    P: KemParams,
178{
179    fn from(seed: Seed) -> Self {
180        Self::from_seed(seed)
181    }
182}
183
184impl<P> Decapsulate for DecapsulationKey<P>
185where
186    P: Kem<EncapsulationKey = EncapsulationKey<P>, SharedKeySize = U32> + KemParams,
187{
188    fn decapsulate(&self, encapsulated_key: &Ciphertext<P>) -> SharedKey {
189        let mp = self.dk_pke.decrypt(encapsulated_key);
190        let (Kp, rp) = G(&[&mp, &self.ek.h()]);
191        let Kbar = J(&[self.z.as_slice(), encapsulated_key.as_ref()]);
192        let cp = self.ek.ek_pke().encrypt(&mp, &rp);
193        Kbar.ct_select(&Kp, cp.ct_eq(encapsulated_key))
194    }
195}
196
197impl<P> Decapsulator for DecapsulationKey<P>
198where
199    P: Kem<EncapsulationKey = EncapsulationKey<P>, SharedKeySize = U32> + KemParams,
200{
201    type Kem = P;
202
203    fn encapsulation_key(&self) -> &EncapsulationKey<P> {
204        &self.ek
205    }
206}
207
208impl<P> Generate for DecapsulationKey<P>
209where
210    P: KemParams,
211{
212    fn try_generate_from_rng<R>(rng: &mut R) -> Result<Self, <R as TryRng>::Error>
213    where
214        R: TryCryptoRng + ?Sized,
215    {
216        Self::try_generate_from_rng(rng)
217    }
218}
219
220impl<P> KeySizeUser for DecapsulationKey<P>
221where
222    P: KemParams,
223{
224    type KeySize = U64;
225}
226
227/// Initialize [`DecapsulationKey`] from a 64-byte uniformly random [`Seed`] value.
228impl<P> KeyInit for DecapsulationKey<P>
229where
230    P: KemParams,
231{
232    #[inline]
233    fn new(seed: &Seed) -> Self {
234        Self::from_seed(*seed)
235    }
236}
237
238/// Serialize the 64-byte [`Seed`] value used to initialize this [`DecapsulationKey`].
239///
240/// # Panics
241/// If this [`DecapsulationKey`] was initialized using legacy expanded key support
242/// (see [`ExpandedKeyEncoding`]).
243impl<P> KeyExport for DecapsulationKey<P>
244where
245    P: KemParams,
246{
247    fn to_bytes(&self) -> Seed {
248        self.to_seed().expect("should be initialized from a seed")
249    }
250}
251
252/// DEPRECATED: support for encoding and decoding [`DecapsulationKey`]s in the legacy expanded form,
253/// as opposed to the more widely adopted [`Seed`] form.
254///
255/// The expanded encoding format is problematic for several reasons, notably they need to validated
256/// whereas generation from seeds is always correct, meaning there is no performance advantage to
257/// using them, only additional complexity.
258///
259/// They are significantly larger than seeds (which are 64-bytes) and their sizes vary depending on
260/// security level whereas the size of a seed is constant:
261/// - ML-KEM-512: 1632 bytes
262/// - ML-KEM-768: 2400 bytes
263/// - ML-KEM-1024: 3168 bytes
264///
265/// Many ML-KEM libraries have dropped support for this format entirely.
266#[deprecated(since = "0.3.0", note = "use `DecapsulationKey::from_seed` instead")]
267pub trait ExpandedKeyEncoding: Sized {
268    /// The size of an expanded decapsulation key.
269    type EncodedSize: ArraySize;
270
271    /// Parse a [`DecapsulationKey`] from its legacy expanded form.
272    ///
273    /// # Errors
274    /// - If the key fails to validate successfully.
275    fn from_expanded_bytes(enc: &Array<u8, Self::EncodedSize>) -> Result<Self, InvalidKey>;
276
277    /// Serialize a [`DecapsulationKey`] to its legacy expanded form.
278    fn to_expanded_bytes(&self) -> Array<u8, Self::EncodedSize>;
279}
280
281#[allow(deprecated)]
282impl<P> ExpandedKeyEncoding for DecapsulationKey<P>
283where
284    P: KemParams,
285{
286    type EncodedSize = DecapsulationKeySize<P>;
287
288    fn from_expanded_bytes(expanded: &ExpandedDecapsulationKey<P>) -> Result<Self, InvalidKey> {
289        Self::from_expanded(expanded)
290    }
291
292    fn to_expanded_bytes(&self) -> ExpandedDecapsulationKey<P> {
293        let dk_pke = self.dk_pke.to_bytes();
294        let ek = self.ek.to_bytes();
295        P::concat_dk(dk_pke, ek, self.ek.h(), *self.z)
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302    use crate::{MlKem512, MlKem768, MlKem1024};
303
304    fn key_equality<P: KemParams>() {
305        let key = DecapsulationKey::<P>::from_seed([0; 64].into());
306        let other = DecapsulationKey::<P>::from_seed([1; 64].into());
307
308        // Changing any one compared component must make the keys unequal.
309        let mut changed = key.clone();
310        changed.dk_pke = other.dk_pke.clone();
311        assert_ne!(key, changed);
312
313        let mut changed = key.clone();
314        changed.ek = other.ek.clone();
315        assert_ne!(key, changed);
316
317        for i in [0, 31] {
318            let mut changed = key.clone();
319            changed.z[i] ^= 1;
320            assert_ne!(key, changed);
321        }
322
323        // Seed provenance is deliberately omitted from equality.
324        let mut imported = key.clone();
325        imported.d = None;
326        assert_eq!(key, imported);
327    }
328
329    #[test]
330    fn equality_compares_all_key_components() {
331        key_equality::<MlKem512>();
332        key_equality::<MlKem768>();
333        key_equality::<MlKem1024>();
334    }
335}