capsule_core/crypto/keys/kem_p256.rs
1//! The **hardware-bound P-256 variant** of the Device Encryption Key (DEK); design:
2//! <https://docs/design/cryptography/keys/#device-keys>.
3//!
4//! The software DEK is **X-Wing** (X25519 + ML-KEM-768; see [`super::kem`]). Shipping secure
5//! elements expose **ECDH-P256**, not X25519, so — mirroring the P-256 hybrid **signing** key
6//! ([`super::p256`]) — the hardware-backed DEK replaces the X25519 classical half with a
7//! *hardware-held P-256 key* while the post-quantum **ML-KEM-768** half stays software-sealed
8//! (no shipping element holds PQ keys). The doc pins the composition (`keys.md` §Device Keys):
9//!
10//! > **DEK** (Device Encryption Key): hybrid **X25519 + ML-KEM-768**. … The **classical half** …
11//! > is **generated inside and never leaves hardware** … the **PQ half** (… ML-KEM-768) is
12//! > software-sealed … Shipping elements also expose **P-256**, not Ed25519/X25519, so the
13//! > hardware-backed composition is the planned **P-256 hybrid variant**.
14//!
15//! ## Composition
16//!
17//! The hybrid mirrors the X-Wing combiner structure, substituting the P-256 ECDH half for the
18//! X25519 half (the classical half is the *only* thing that changes, exactly as the DSK's P-256
19//! variant swaps ECDSA-P256 for Ed25519):
20//!
21//! - **public key** `ek_M (1184) ‖ pk_P (65, uncompressed SEC1)`
22//! - **ciphertext** `ct_M (1088) ‖ ct_P (65, the sender's ephemeral P-256 public key)`
23//! - **shared secret** `SHA3-256(ss_M ‖ ss_P ‖ ct_P ‖ pk_P ‖ label)`, where `ss_M` is the ML-KEM
24//! shared secret and `ss_P` is the raw 32-byte P-256 ECDH secret (the point's x-coordinate).
25//!
26//! A distinct domain-separation `label` ([`P256_HYBRID_LABEL`]) is bound in place of X-Wing's, so
27//! a P-256-variant ciphertext and an X-Wing ciphertext can never derive the same secret. The
28//! algorithm is **tagged by length**: the P-256 public/ciphertext are 65-byte-classical-half
29//! longer than X-Wing's 32-byte-classical-half forms, so the two never alias and the existing
30//! X-Wing bytes ([`super::kem`]) are unchanged — the X25519 path is byte-for-byte identical.
31//!
32//! The classical half is reached through the [`HardwareKeyAgreement`] seam: [`P256HybridDek::enroll`]
33//! reads the element's static P-256 public key, and [`P256HybridDek::decapsulate`] asks the element
34//! to ECDH the sender's ephemeral public key — so the private P-256 scalar never leaves hardware.
35//! **Encapsulation is pure software** (the sender holds only the recipient's public bytes), matching
36//! [`super::kem::encapsulate_to_public`].
37
38use std::sync::Arc;
39
40use ml_kem::kem::Decapsulate;
41use ml_kem::{B32, DecapsulationKey, EncapsulationKey, Key, KeyExport, MlKem768, Seed};
42use p256::elliptic_curve::sec1::ToEncodedPoint;
43use sha3::{Digest, Sha3_256};
44use shake::{ExtendableOutput, Shake256, Update, XofReader};
45
46use super::hardware::{HardwareKeyAgreement, HardwareSignerError};
47use crate::crypto::{CryptoError, rng};
48
49/// ML-KEM-768 encapsulation-key length (the `ek_M` prefix).
50const MLKEM_PK_LEN: usize = 1184;
51/// ML-KEM-768 ciphertext length (the `ct_M` prefix).
52const MLKEM_CT_LEN: usize = 1088;
53/// Uncompressed SEC1 (x9.63) P-256 point length (`0x04‖x‖y`) — the wire form of `pk_P` / `ct_P`.
54const P256_POINT_LEN: usize = 65;
55/// Raw P-256 ECDH shared-secret length (the 32-byte big-endian x-coordinate).
56const P256_SS_LEN: usize = 32;
57
58/// P-256-hybrid DEK public-key length: `ek_M (1184) ‖ pk_P (65)`.
59pub const DEK_P256_PUBLIC_LEN: usize = MLKEM_PK_LEN + P256_POINT_LEN;
60/// P-256-hybrid DEK ciphertext length: `ct_M (1088) ‖ ct_P (65)`.
61pub const DEK_P256_CIPHERTEXT_LEN: usize = MLKEM_CT_LEN + P256_POINT_LEN;
62
63/// Domain-separation label for the P-256 hybrid KEM combiner. Distinct from X-Wing's 6-byte label
64/// so a P-256-variant ciphertext and an X-Wing ciphertext can never combine to the same secret.
65const P256_HYBRID_LABEL: &[u8] = b"Capsule-P256-hybrid-KEM-v1";
66
67fn to_32(bytes: &[u8]) -> [u8; 32] {
68 let mut out = [0u8; 32];
69 out.copy_from_slice(bytes);
70 out
71}
72
73/// Parse an uncompressed-SEC1 (or compressed) P-256 public key.
74fn parse_p256_public(point: &[u8]) -> Result<p256::PublicKey, CryptoError> {
75 p256::PublicKey::from_sec1_bytes(point)
76 .map_err(|_| CryptoError::Key("invalid P-256 public key"))
77}
78
79/// Uncompressed-SEC1 bytes for a P-256 public key (`0x04‖x‖y`, 65 bytes).
80fn uncompressed(pk: &p256::PublicKey) -> Vec<u8> {
81 pk.to_encoded_point(false).as_bytes().to_vec()
82}
83
84/// The hybrid combiner: bind both shared secrets, the P-256 ciphertext (ephemeral public key), and
85/// the recipient's static P-256 public key under SHA3-256 with the domain-separating label. Mirrors
86/// the X-Wing combiner ([`super::kem`]) with the P-256 ECDH half substituted for the X25519 half.
87fn combiner(ss_m: &[u8], ss_p: &[u8; P256_SS_LEN], ct_p: &[u8], pk_p: &[u8]) -> [u8; 32] {
88 let mut h = Sha3_256::new();
89 Digest::update(&mut h, ss_m);
90 Digest::update(&mut h, ss_p);
91 Digest::update(&mut h, ct_p);
92 Digest::update(&mut h, pk_p);
93 Digest::update(&mut h, P256_HYBRID_LABEL);
94 to_32(&h.finalize())
95}
96
97/// Expand a 32-byte software seed to the 64-byte ML-KEM-768 `d‖z` seed (SHAKE256), matching how
98/// the X-Wing DEK derives its ML-KEM half. Only the ML-KEM half is seed-derived; the classical
99/// half is hardware-held and non-exportable, so it is not part of any sealed seed.
100fn mlkem_from_seed(ml_seed: &[u8; 32]) -> DecapsulationKey<MlKem768> {
101 let mut xof = Shake256::default();
102 xof.update(ml_seed);
103 let mut reader = xof.finalize_xof();
104 let mut dz = [0u8; 64];
105 reader.read(&mut dz);
106 let s = Seed::try_from(&dz[..]).expect("64-byte ML-KEM seed");
107 DecapsulationKey::<MlKem768>::from_seed(s)
108}
109
110/// A device encryption keypair whose **classical half is a hardware-held P-256 key** and whose
111/// ML-KEM-768 half is software-sealed. The KEM analogue of
112/// [`P256HybridSigningKey`](super::p256::P256HybridSigningKey), and the hardware-bound counterpart
113/// of the software X-Wing [`DekKeypair`](super::kem::DekKeypair).
114pub struct P256HybridDek {
115 agreement: Arc<dyn HardwareKeyAgreement>,
116 key_alias: String,
117 /// The 32-byte software seed the ML-KEM-768 half was expanded from. Retained so the keystore
118 /// can seal it under the master key and re-derive this half on unlock; the classical
119 /// half needs no seed because it never leaves the element.
120 ml_seed: [u8; 32],
121 /// ML-KEM-768 decapsulation key (software half).
122 dk: DecapsulationKey<MlKem768>,
123 /// The element's static P-256 public key (`pk_P`) — the private scalar stays in hardware.
124 p256_public: p256::PublicKey,
125}
126
127impl P256HybridDek {
128 /// Enroll a P-256 key-agreement key under `key_alias` in `hardware` and compose it with the
129 /// software ML-KEM-768 half derived from `ml_seed` (the software-sealed 32-byte seed). Reads
130 /// the element's static P-256 public key and builds the published hybrid public key from it
131 /// plus the ML-KEM-768 encapsulation key.
132 pub fn enroll(
133 hardware: Arc<dyn HardwareKeyAgreement>,
134 key_alias: String,
135 ml_seed: &[u8; 32],
136 ) -> Result<Self, HardwareSignerError> {
137 let point = hardware.enroll(key_alias.clone())?;
138 let p256_public = parse_p256_public(&point)
139 .map_err(|_| HardwareSignerError::Backend("bad P-256 key".into()))?;
140 Ok(Self {
141 agreement: hardware,
142 key_alias,
143 ml_seed: *ml_seed,
144 dk: mlkem_from_seed(ml_seed),
145 p256_public,
146 })
147 }
148
149 /// The element alias this DEK's classical half is enrolled under. Persisted (in the clear —
150 /// it is a lookup handle, not a secret) in the [`AccountFile`](super::keystore::AccountFile)
151 /// so a reopened workspace can re-bind to the same hardware key.
152 pub fn key_alias(&self) -> &str {
153 &self.key_alias
154 }
155
156 /// The 32-byte software seed of the ML-KEM-768 half — the value the keystore seals under the
157 /// master key, mirroring [`DekKeypair::to_seed_bytes`](super::kem::DekKeypair::to_seed_bytes).
158 /// The classical half is *not* covered: it is hardware-held and non-exportable by contract,
159 /// which is exactly why a hardware-bound device cannot be restored from a backup.
160 pub fn to_ml_seed_bytes(&self) -> [u8; 32] {
161 self.ml_seed
162 }
163
164 /// The published hybrid public-encapsulation-key bytes `ek_M ‖ pk_P` (for the device directory).
165 pub fn public_bytes(&self) -> Vec<u8> {
166 let mut out = Vec::with_capacity(DEK_P256_PUBLIC_LEN);
167 out.extend_from_slice(self.dk.encapsulation_key().to_bytes().as_slice());
168 out.extend_from_slice(&uncompressed(&self.p256_public));
169 out
170 }
171
172 /// Decapsulate a P-256-hybrid ciphertext `ct_M ‖ ct_P`, recovering the 32-byte shared secret
173 /// (receiver side). The ML-KEM half is decapsulated in software; the P-256 half is ECDH'd
174 /// **inside the hardware element** against the sender's ephemeral public key `ct_P`. A
175 /// wrong-length ciphertext is rejected; a foreign ML-KEM ciphertext recovers a different
176 /// pseudo-random secret (ML-KEM implicit rejection), never an error.
177 pub fn decapsulate(&self, ciphertext: &[u8]) -> Result<[u8; 32], CryptoError> {
178 if ciphertext.len() != DEK_P256_CIPHERTEXT_LEN {
179 return Err(CryptoError::Malformed(
180 "P-256 hybrid ciphertext wrong length",
181 ));
182 }
183 let (ct_m, ct_p) = ciphertext.split_at(MLKEM_CT_LEN);
184
185 let ss_m = self
186 .dk
187 .decapsulate_slice(ct_m)
188 .map_err(|_| CryptoError::Malformed("ML-KEM ciphertext wrong length"))?;
189
190 // The hardware element performs the ECDH; the raw 32-byte x-coordinate comes back.
191 let ss_p_bytes = self
192 .agreement
193 .key_agreement(self.key_alias.clone(), ct_p.to_vec())
194 .map_err(|_| CryptoError::Auth("hardware P-256 ECDH failed"))?;
195 if ss_p_bytes.len() != P256_SS_LEN {
196 return Err(CryptoError::Malformed(
197 "hardware ECDH secret must be 32 bytes",
198 ));
199 }
200 let ss_p = to_32(&ss_p_bytes);
201 let pk_p = uncompressed(&self.p256_public);
202
203 Ok(combiner(ss_m.as_slice(), &ss_p, ct_p, &pk_p))
204 }
205}
206
207impl std::fmt::Debug for P256HybridDek {
208 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
209 f.write_str("P256HybridDek(****)")
210 }
211}
212
213/// Encapsulate a fresh shared secret to a **foreign** P-256-hybrid public key `ek_M ‖ pk_P` — the
214/// sender side, holding only the recipient's public half. Pure software (no hardware): it mirrors
215/// [`super::kem::encapsulate_to_public`] for the P-256 variant. Returns the ciphertext
216/// `ct_M ‖ ct_P` ([`DEK_P256_CIPHERTEXT_LEN`] bytes) and the 32-byte combined shared secret.
217///
218/// A wrong-length `public_bytes`, or one whose ML-KEM/P-256 half fails decoding, is rejected.
219pub fn encapsulate_to_p256_public(public_bytes: &[u8]) -> Result<(Vec<u8>, [u8; 32]), CryptoError> {
220 encapsulate_to_p256_public_derand(
221 public_bytes,
222 &rng::random_array::<32>(),
223 random_p256_secret(),
224 )
225}
226
227/// Draw a valid random P-256 secret scalar from the OS CSPRNG. `from_slice` rejects the vanishing
228/// fraction of 32-byte draws that fall outside `[1, n-1]`; the loop re-draws (expected ~1 attempt).
229fn random_p256_secret() -> p256::SecretKey {
230 loop {
231 if let Ok(sk) = p256::SecretKey::from_slice(&rng::random_array::<32>()) {
232 return sk;
233 }
234 }
235}
236
237/// Derandomized [`encapsulate_to_p256_public`]: `mlkem_coin` is the ML-KEM encapsulation coin `m`
238/// and `ephemeral` is the sender's P-256 ephemeral secret. Exposed within the crate for
239/// deterministic round-trip testing; the public path draws both from the OS CSPRNG.
240pub(crate) fn encapsulate_to_p256_public_derand(
241 public_bytes: &[u8],
242 mlkem_coin: &[u8; 32],
243 ephemeral: p256::SecretKey,
244) -> Result<(Vec<u8>, [u8; 32]), CryptoError> {
245 if public_bytes.len() != DEK_P256_PUBLIC_LEN {
246 return Err(CryptoError::Malformed(
247 "P-256 hybrid public key wrong length",
248 ));
249 }
250 let (ek_bytes, pk_p_bytes) = public_bytes.split_at(MLKEM_PK_LEN);
251
252 // ML-KEM-768 half: reconstruct the recipient's encapsulation key and derandomize-encapsulate.
253 let ek_encoded = Key::<EncapsulationKey<MlKem768>>::try_from(ek_bytes)
254 .map_err(|_| CryptoError::Malformed("ML-KEM public key wrong length"))?;
255 let ek = EncapsulationKey::<MlKem768>::new(&ek_encoded)
256 .map_err(|_| CryptoError::Key("invalid ML-KEM public key"))?;
257 let m = B32::try_from(&mlkem_coin[..]).expect("32-byte m");
258 let (ct_m, ss_m) = ek.encapsulate_deterministic(&m);
259
260 // P-256 half: `ct_P` is the ephemeral public key; `ss_P` is ECDH against the recipient's
261 // static `pk_P`.
262 let recipient = parse_p256_public(pk_p_bytes)?;
263 let ct_p = uncompressed(&ephemeral.public_key());
264 let shared = p256::ecdh::diffie_hellman(ephemeral.to_nonzero_scalar(), recipient.as_affine());
265 let ss_p = to_32(shared.raw_secret_bytes().as_slice());
266 let pk_p = uncompressed(&recipient);
267
268 let ss = combiner(ss_m.as_slice(), &ss_p, &ct_p, &pk_p);
269 let mut ct = Vec::with_capacity(DEK_P256_CIPHERTEXT_LEN);
270 ct.extend_from_slice(ct_m.as_slice());
271 ct.extend_from_slice(&ct_p);
272 Ok((ct, ss))
273}
274
275/// An in-memory stand-in for a P-256 key-agreement secure element (Secure Enclave / StrongBox /
276/// TPM). The software `p256` crate is the reference the real element replaces: it holds the static
277/// P-256 key, exposes its public key as uncompressed SEC1 (`0x04‖x‖y`, the form Secure Enclave's
278/// `P256.KeyAgreement` emits), and ECDHs against a peer's ephemeral public key. Test-only; a real
279/// element keeps the scalar in hardware. Shared with the `verify_asset`/FFI tests, so it lives
280/// outside the `tests` module (mirroring `MockP256Element`).
281#[cfg(any(test, feature = "test-support"))]
282pub struct MockP256KeyAgreement {
283 sk: p256::SecretKey,
284 exportable: bool,
285}
286
287#[cfg(any(test, feature = "test-support"))]
288impl MockP256KeyAgreement {
289 /// A mock element over `scalar`/`seed`; `exportable` makes it fail the non-exportability assertion.
290 pub fn new(scalar: [u8; 32], exportable: bool) -> Self {
291 Self {
292 sk: p256::SecretKey::from_slice(&scalar).expect("valid P-256 scalar"),
293 exportable,
294 }
295 }
296}
297
298#[cfg(any(test, feature = "test-support"))]
299impl HardwareKeyAgreement for MockP256KeyAgreement {
300 fn enroll(&self, alias: String) -> Result<Vec<u8>, HardwareSignerError> {
301 self.public_key(alias)
302 }
303 fn public_key(&self, _alias: String) -> Result<Vec<u8>, HardwareSignerError> {
304 Ok(uncompressed(&self.sk.public_key()))
305 }
306 fn key_agreement(
307 &self,
308 _alias: String,
309 peer_public: Vec<u8>,
310 ) -> Result<Vec<u8>, HardwareSignerError> {
311 let peer = p256::PublicKey::from_sec1_bytes(&peer_public)
312 .map_err(|_| HardwareSignerError::Backend("bad peer P-256 key".into()))?;
313 let shared = p256::ecdh::diffie_hellman(self.sk.to_nonzero_scalar(), peer.as_affine());
314 Ok(shared.raw_secret_bytes().as_slice().to_vec())
315 }
316 fn assert_non_exportable(&self, _alias: String) -> Result<(), HardwareSignerError> {
317 if self.exportable {
318 Err(HardwareSignerError::Exportable)
319 } else {
320 Ok(())
321 }
322 }
323}
324
325#[cfg(test)]
326mod tests;