Skip to main content

capsule_core/crypto/keys/
kem.rs

1//! The Device Encryption Key (DEK) — an **X-Wing** hybrid KEM keypair (X25519 + ML-KEM-768).
2//!
3//! The DEK is the device's key-encapsulation key: a sender encapsulates a shared secret
4//! to the device's public key, and the device decapsulates it with its private key. In
5//! Capsule it carries key wraps to a device and underlies MLS HPKE
6//! (SSoT: [Cryptography — Keys § Device Keys], [Primitives § KEM]).
7//!
8//! This is the hybrid the design's `crypto_suite_id = 0x0001` declares: **X-Wing**
9//! (`draft-connolly-cfrg-xwing-kem`), combining the post-quantum **ML-KEM-768** half with the
10//! classical **X25519** half so neither being broken alone compromises the shared secret. Both
11//! halves are bound into a single 32-byte secret by the X-Wing combiner
12//! `SHA3-256(ss_M ‖ ss_X ‖ ct_X ‖ pk_X ‖ XWingLabel)`.
13//!
14//! Keys are deterministic from a 32-byte seed (X-Wing's secret key), so the DEK persists and
15//! restores verbatim. The seam (`encapsulate`/`decapsulate` over byte strings) is unchanged
16//! from the earlier ML-KEM-only stand-in, so callers are unaffected by the upgrade.
17//!
18//! [Cryptography — Keys § Device Keys]: https://docs/design/cryptography/keys/#device-keys
19//! [Primitives § KEM]: https://docs/design/cryptography/primitives/#kem
20
21use ml_kem::kem::Decapsulate;
22use ml_kem::{B32, DecapsulationKey, EncapsulationKey, Key, KeyExport, MlKem768, Seed};
23use sha3::{Digest, Sha3_256};
24use shake::{ExtendableOutput, Shake256, Update, XofReader};
25use x25519_dalek::{X25519_BASEPOINT_BYTES, x25519};
26
27use crate::crypto::{CryptoError, rng};
28
29/// Length of the X-Wing secret-key seed. SHAKE256-expanded to 96 bytes: the ML-KEM-768 seed
30/// `d ‖ z` (64) and the X25519 secret scalar (32).
31pub(crate) const DEK_SEED_LEN: usize = 32;
32
33/// X-Wing public-key length: `pk_M (1184) ‖ pk_X (32)`.
34pub const DEK_PUBLIC_LEN: usize = 1184 + 32;
35/// X-Wing ciphertext length: `ct_M (1088) ‖ ct_X (32)`.
36pub const DEK_CIPHERTEXT_LEN: usize = 1088 + 32;
37/// Length of the X-Wing encapsulation seed: ML-KEM coins `m` (32) and the X25519 ephemeral (32).
38pub const ESEED_LEN: usize = 64;
39const MLKEM_CT_LEN: usize = 1088;
40/// ML-KEM-768 encapsulation-key length (the `pk_M` prefix of an X-Wing public key).
41const MLKEM_PK_LEN: usize = 1184;
42
43/// The X-Wing combiner label: the 6-byte ASCII art `\.//^\` (`5c2e2f2f5e5c`).
44const XWING_LABEL: [u8; 6] = [0x5c, 0x2e, 0x2f, 0x2f, 0x5e, 0x5c];
45
46/// A device encryption keypair (X-Wing = X25519 + ML-KEM-768). Holds both private halves; the
47/// public encapsulation key is derived on demand.
48pub struct DekKeypair {
49    /// The 32-byte X-Wing secret-key seed (the value sealed in the keystore).
50    seed: [u8; DEK_SEED_LEN],
51    /// ML-KEM-768 decapsulation key, derived from the seed.
52    dk: DecapsulationKey<MlKem768>,
53    /// X25519 secret scalar, derived from the seed.
54    sk_x: [u8; 32],
55}
56
57fn shared_to_32(bytes: &[u8]) -> [u8; 32] {
58    let mut out = [0u8; 32];
59    out.copy_from_slice(bytes);
60    out
61}
62
63/// The X-Wing combiner: bind both shared secrets, the X25519 ciphertext, and the recipient's
64/// static X25519 public key under SHA3-256 with the domain-separating label.
65fn combiner(ss_m: &[u8], ss_x: &[u8; 32], ct_x: &[u8; 32], pk_x: &[u8; 32]) -> [u8; 32] {
66    let mut h = Sha3_256::new();
67    Digest::update(&mut h, ss_m);
68    Digest::update(&mut h, ss_x);
69    Digest::update(&mut h, ct_x);
70    Digest::update(&mut h, pk_x);
71    Digest::update(&mut h, XWING_LABEL);
72    shared_to_32(&h.finalize())
73}
74
75impl DekKeypair {
76    /// Generate a fresh DEK from the OS CSPRNG.
77    pub fn generate() -> Self {
78        Self::from_seed(&rng::random_array::<DEK_SEED_LEN>())
79    }
80
81    /// Reconstruct deterministically from the 32-byte X-Wing seed (`expandDecapsulationKey`).
82    pub fn from_seed(seed: &[u8; DEK_SEED_LEN]) -> Self {
83        // expanded = SHAKE256(seed, 96): [0:64] = ML-KEM d‖z, [64:96] = X25519 scalar.
84        let mut xof = Shake256::default();
85        xof.update(seed);
86        let mut reader = xof.finalize_xof();
87        let mut expanded = [0u8; 96];
88        reader.read(&mut expanded);
89
90        let s = Seed::try_from(&expanded[..64]).expect("64-byte ML-KEM seed");
91        let dk = DecapsulationKey::<MlKem768>::from_seed(s);
92        let sk_x = shared_to_32(&expanded[64..96]);
93        Self {
94            seed: *seed,
95            dk,
96            sk_x,
97        }
98    }
99
100    /// Export the 32-byte X-Wing seed for sealed storage in the keystore.
101    pub fn to_seed_bytes(&self) -> [u8; DEK_SEED_LEN] {
102        self.seed
103    }
104
105    /// This device's static X25519 public key (`pk_X = X25519(sk_X, base)`).
106    fn pk_x(&self) -> [u8; 32] {
107        x25519(self.sk_x, X25519_BASEPOINT_BYTES)
108    }
109
110    /// The X-Wing public encapsulation-key bytes `pk_M ‖ pk_X` (for the device directory).
111    pub fn public_bytes(&self) -> Vec<u8> {
112        let mut out = Vec::with_capacity(DEK_PUBLIC_LEN);
113        out.extend_from_slice(self.dk.encapsulation_key().to_bytes().as_slice());
114        out.extend_from_slice(&self.pk_x());
115        out
116    }
117
118    /// Encapsulate a fresh shared secret to this keypair's own public key, returning the
119    /// X-Wing ciphertext `ct_M ‖ ct_X` and the 32-byte combined shared secret (sender side).
120    pub fn encapsulate_to_self(&self) -> (Vec<u8>, [u8; 32]) {
121        self.encapsulate_to_self_derand(&rng::random_array::<ESEED_LEN>())
122    }
123
124    /// Derandomized encapsulation to self (the X-Wing `EncapsDerand` with explicit `eseed`):
125    /// `eseed[0:32]` is the ML-KEM coin `m`, `eseed[32:64]` the X25519 ephemeral scalar.
126    /// Exposed for known-answer testing; the public path draws `eseed` from the OS CSPRNG.
127    fn encapsulate_to_self_derand(&self, eseed: &[u8; ESEED_LEN]) -> (Vec<u8>, [u8; 32]) {
128        let pk_x = self.pk_x();
129
130        // ML-KEM-768 half: derandomized encapsulation to our own encapsulation key.
131        let m = B32::try_from(&eseed[..32]).expect("32-byte m");
132        let (ct_m, ss_m) = self.dk.encapsulation_key().encapsulate_deterministic(&m);
133
134        // X25519 half: ephemeral scalar from eseed[32:64]; ct_X is its public key.
135        let eph = shared_to_32(&eseed[32..64]);
136        let ct_x = x25519(eph, X25519_BASEPOINT_BYTES);
137        let ss_x = x25519(eph, pk_x);
138
139        let ss = combiner(ss_m.as_slice(), &ss_x, &ct_x, &pk_x);
140        let mut ct = Vec::with_capacity(DEK_CIPHERTEXT_LEN);
141        ct.extend_from_slice(ct_m.as_slice());
142        ct.extend_from_slice(&ct_x);
143        (ct, ss)
144    }
145
146    /// Decapsulate an X-Wing ciphertext `ct_M ‖ ct_X`, recovering the 32-byte shared secret
147    /// (receiver side). A wrong-length ciphertext is rejected; a foreign ciphertext recovers a
148    /// different pseudo-random secret (ML-KEM implicit rejection), never an error.
149    pub fn decapsulate(&self, ciphertext: &[u8]) -> Result<[u8; 32], CryptoError> {
150        if ciphertext.len() != DEK_CIPHERTEXT_LEN {
151            return Err(CryptoError::Malformed("X-Wing ciphertext wrong length"));
152        }
153        let (ct_m, ct_x_bytes) = ciphertext.split_at(MLKEM_CT_LEN);
154
155        let ss_m = self
156            .dk
157            .decapsulate_slice(ct_m)
158            .map_err(|_| CryptoError::Malformed("ML-KEM ciphertext wrong length"))?;
159
160        let ct_x = shared_to_32(ct_x_bytes);
161        let pk_x = self.pk_x();
162        let ss_x = x25519(self.sk_x, ct_x);
163
164        Ok(combiner(ss_m.as_slice(), &ss_x, &ct_x, &pk_x))
165    }
166}
167
168/// Encapsulate a fresh shared secret to a **foreign** X-Wing public key `pk_M ‖ pk_X` —
169/// the sender side when you hold only the recipient's public half (e.g. a web-upload guest
170/// sealing an asset key to the link's Drop Key, which travels in the URL fragment). Returns
171/// the X-Wing ciphertext `ct_M ‖ ct_X` ([`DEK_CIPHERTEXT_LEN`] bytes) and the 32-byte
172/// combined shared secret. Draws the encapsulation randomness from the OS CSPRNG.
173///
174/// A wrong-length `public_bytes`, or one whose ML-KEM half fails decoding, is rejected
175/// ([`CryptoError::Malformed`] / [`CryptoError::Key`]).
176pub fn encapsulate_to_public(public_bytes: &[u8]) -> Result<(Vec<u8>, [u8; 32]), CryptoError> {
177    encapsulate_to_public_derand(public_bytes, &rng::random_array::<ESEED_LEN>())
178}
179
180/// Derandomized [`encapsulate_to_public`] (X-Wing `EncapsDerand` to a foreign key): `eseed`
181/// is the ML-KEM coin `m` (`[0:32]`) and the X25519 ephemeral scalar (`[32:64]`). Exposed
182/// within the crate for known-answer/round-trip testing; the public path draws `eseed`
183/// from the OS CSPRNG.
184pub(crate) fn encapsulate_to_public_derand(
185    public_bytes: &[u8],
186    eseed: &[u8; ESEED_LEN],
187) -> Result<(Vec<u8>, [u8; 32]), CryptoError> {
188    if public_bytes.len() != DEK_PUBLIC_LEN {
189        return Err(CryptoError::Malformed("X-Wing public key wrong length"));
190    }
191    let (pk_m_bytes, pk_x_bytes) = public_bytes.split_at(MLKEM_PK_LEN);
192
193    // Reconstruct the recipient's ML-KEM-768 encapsulation key from its serialized form.
194    let ek_encoded = Key::<EncapsulationKey<MlKem768>>::try_from(pk_m_bytes)
195        .map_err(|_| CryptoError::Malformed("ML-KEM public key wrong length"))?;
196    let ek = EncapsulationKey::<MlKem768>::new(&ek_encoded)
197        .map_err(|_| CryptoError::Key("invalid ML-KEM public key"))?;
198
199    let pk_x = shared_to_32(pk_x_bytes);
200
201    // ML-KEM-768 half: derandomized encapsulation to the recipient's encapsulation key.
202    let m = B32::try_from(&eseed[..32]).expect("32-byte m");
203    let (ct_m, ss_m) = ek.encapsulate_deterministic(&m);
204
205    // X25519 half: ephemeral scalar from eseed[32:64]; ct_X is its public key; the shared
206    // secret is against the recipient's static X25519 public key `pk_X`.
207    let eph = shared_to_32(&eseed[32..64]);
208    let ct_x = x25519(eph, X25519_BASEPOINT_BYTES);
209    let ss_x = x25519(eph, pk_x);
210
211    let ss = combiner(ss_m.as_slice(), &ss_x, &ct_x, &pk_x);
212    let mut ct = Vec::with_capacity(DEK_CIPHERTEXT_LEN);
213    ct.extend_from_slice(ct_m.as_slice());
214    ct.extend_from_slice(&ct_x);
215    Ok((ct, ss))
216}
217
218impl Clone for DekKeypair {
219    fn clone(&self) -> Self {
220        Self::from_seed(&self.to_seed_bytes())
221    }
222}
223
224impl std::fmt::Debug for DekKeypair {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        f.write_str("DekKeypair(****)")
227    }
228}
229
230#[cfg(test)]
231mod tests;