//! X-Wing: the hybrid KEM ML-KEM-768 + X25519, as specified in draft-connolly-cfrg-xwing-kem-11. //! //! This module is glue between vetted primitives: ML-KEM-768 from `ml-kem` (FIPS 203), X25519 from //! `x25519-dalek` (RFC 7748), SHAKE256 from `shake` and SHA3-256 from `sha3` (FIPS 202). It is pinned //! by the draft's three test vectors and a differential test against RustCrypto's `x-wing` crate. //! //! Two deliberate differences from the draft, both stricter and both invisible to honest peers and //! to the official vectors: a low-order X25519 public key or ciphertext part is refused with //! [`Error::NonContributory`], and a public key whose X25519 half is not the canonical encoding //! (bit 255 set, or a value of at least 2^255 - 19) is refused with [`Error::InvalidPublicKey`] //! (docs/01_arcanum.md). //! //! **The raw one-way KEM is not part of the release API** (QA R2-01). Without the `hazmat` feature //! a consumer can parse keys and ciphertexts and generate a key pair, but cannot encapsulate, //! decapsulate or read an X-Wing secret: a PSK must come from [`crate::exchange`], which needs both //! directions and binds the transcript, and sealing goes through [`crate::seal`]. use core::{array, fmt}; use ml_kem::array::Array; use ml_kem::{B32, Decapsulate, KeyExport, MlKem768, Seed}; use rand_core::CryptoRng; use sha3::{Digest, Sha3_256}; use shake::{ExtendableOutput, Shake256, Update, XofReader}; use x25519_dalek::{PublicKey as X25519Public, StaticSecret}; use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing}; use crate::error::{Error, Input, exact}; type MlKemEncapsulationKey = ml_kem::EncapsulationKey; type MlKemDecapsulationKey = ml_kem::DecapsulationKey; /// Length of a hybrid public key: ML-KEM-768 encapsulation key (1184) + X25519 public key (32). pub const PUBLIC_KEY_LEN: usize = 1216; /// Length of a hybrid secret key: a 32-byte seed, expanded with SHAKE256. pub const SECRET_KEY_LEN: usize = 32; /// Length of a hybrid ciphertext: ML-KEM-768 ciphertext (1088) + X25519 ephemeral public key (32). pub const CIPHERTEXT_LEN: usize = 1120; /// Length of the X-Wing shared secret. pub const SHARED_SECRET_LEN: usize = 32; /// Length of the encapsulation randomness: 32 bytes for ML-KEM, 32 for the X25519 ephemeral key. pub const ENCAPSULATION_SEED_LEN: usize = 64; const ML_KEM_PUBLIC_KEY_LEN: usize = 1184; const ML_KEM_CIPHERTEXT_LEN: usize = 1088; /// The X-Wing label, ASCII `\.//^\` (hex 5c2e2f2f5e5c), draft -11 §5.3. const XWING_LABEL: &[u8; 6] = br"\.//^\"; /// X-Wing Combiner (draft -11 §5.3): SHA3-256(ss_M || ss_X || ct_X || pk_X || XWingLabel). pub(crate) fn combiner(ss_m: &[u8; 32], ss_x: &[u8; 32], ct_x: &[u8; 32], pk_x: &[u8; 32]) -> [u8; SHARED_SECRET_LEN] { let mut h = Sha3_256::new(); Digest::update(&mut h, ss_m); Digest::update(&mut h, ss_x); Digest::update(&mut h, ct_x); Digest::update(&mut h, pk_x); Digest::update(&mut h, XWING_LABEL); h.finalize().into() } /// The X-Wing shared secret. Zeroised on drop; never printed. pub struct SharedSecret(pub(crate) Zeroizing<[u8; SHARED_SECRET_LEN]>); impl SharedSecret { /// The raw 32 bytes. **Hazmat** (feature `hazmat`): a one-way X-Wing secret authenticates only /// the receiver and is bound to no transcript, so it must never be used as a key directly. #[cfg(feature = "hazmat")] #[must_use] pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] { &self.0 } pub(crate) fn bytes(&self) -> &[u8; SHARED_SECRET_LEN] { &self.0 } } impl fmt::Debug for SharedSecret { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("SharedSecret([redacted])") } } impl ZeroizeOnDrop for SharedSecret {} /// A hybrid public key (`pk_M || pk_X`), validated on parse. #[derive(Clone)] pub struct PublicKey { bytes: [u8; PUBLIC_KEY_LEN], pk_m: MlKemEncapsulationKey, pk_x: X25519Public, } impl PublicKey { /// Parse a hybrid public key received from somewhere else. /// /// # Errors /// [`Error::InvalidLength`] if it is not 1216 bytes; [`Error::InvalidPublicKey`] if the ML-KEM /// part fails the FIPS 203 §7.2 encapsulation key check, or the X25519 part is not canonical. pub fn from_bytes(bytes: &[u8]) -> Result { let bytes: &[u8; PUBLIC_KEY_LEN] = exact(Input::PublicKey, bytes)?; let m: [u8; ML_KEM_PUBLIC_KEY_LEN] = array::from_fn(|i| bytes[i]); let pk_m = MlKemEncapsulationKey::new(&Array::from(m)).map_err(|_| Error::InvalidPublicKey)?; let x: [u8; 32] = array::from_fn(|i| bytes[ML_KEM_PUBLIC_KEY_LEN + i]); if !is_canonical_x25519(&x) { return Err(Error::InvalidPublicKey); } Ok(Self { bytes: *bytes, pk_m, pk_x: X25519Public::from(x) }) } /// The 1216-byte encoding. #[must_use] pub fn as_bytes(&self) -> &[u8; PUBLIC_KEY_LEN] { &self.bytes } /// Encapsulate a fresh shared secret to this key. **Hazmat** (feature `hazmat`), see the module /// docs; release code uses [`crate::exchange`] or [`crate::seal`]. /// /// # Errors /// [`Error::NonContributory`] if the X25519 part of the key is a low-order point. #[cfg(feature = "hazmat")] pub fn encapsulate(&self, rng: &mut R) -> Result<(Ciphertext, SharedSecret), Error> { let mut eseed = Zeroizing::new([0u8; ENCAPSULATION_SEED_LEN]); rng.fill_bytes(eseed.as_mut_slice()); self.encapsulate_inner(&eseed) } /// X-Wing `EncapsulateDerand` (draft -11 §5.4.1): the randomness is given explicitly. /// /// **Hazmat** (feature `hazmat`). For known-answer tests. Using the same `eseed` twice gives /// the same secret to anyone who sees both ciphertexts. Use [`PublicKey::encapsulate`]. /// /// # Errors /// [`Error::NonContributory`] if the X25519 part of the key is a low-order point. #[cfg(feature = "hazmat")] pub fn encapsulate_derand( &self, eseed: &[u8; ENCAPSULATION_SEED_LEN], ) -> Result<(Ciphertext, SharedSecret), Error> { self.encapsulate_inner(eseed) } pub(crate) fn encapsulate_inner( &self, eseed: &[u8; ENCAPSULATION_SEED_LEN], ) -> Result<(Ciphertext, SharedSecret), Error> { let mut m = B32::from(array::from_fn::(|i| eseed[i])); let (ct_m, mut ss_m) = self.pk_m.encapsulate_deterministic(&m); m.as_mut_slice().zeroize(); let ek_x: Zeroizing<[u8; 32]> = Zeroizing::new(array::from_fn(|i| eseed[32 + i])); let ek_x = StaticSecret::from(*ek_x); let ct_x = X25519Public::from(&ek_x); let ss_x = ek_x.diffie_hellman(&self.pk_x); drop(ek_x); let result = if ss_x.was_contributory() { let ss_m_arr = as32(&ss_m); Ok(combiner(&ss_m_arr, ss_x.as_bytes(), ct_x.as_bytes(), self.pk_x.as_bytes())) } else { Err(Error::NonContributory) }; ss_m.as_mut_slice().zeroize(); let ss = result?; let mut ct = [0u8; CIPHERTEXT_LEN]; ct[..ML_KEM_CIPHERTEXT_LEN].copy_from_slice(ct_m.as_slice()); ct[ML_KEM_CIPHERTEXT_LEN..].copy_from_slice(ct_x.as_bytes()); Ok((Ciphertext(ct), SharedSecret(Zeroizing::new(ss)))) } } impl PartialEq for PublicKey { fn eq(&self, other: &Self) -> bool { self.bytes == other.bytes } } impl Eq for PublicKey {} impl fmt::Debug for PublicKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PublicKey").field("len", &PUBLIC_KEY_LEN).finish_non_exhaustive() } } /// A hybrid ciphertext (`ct_M || ct_X`). Any 1120 bytes parse; a tampered ML-KEM part is handled /// by implicit rejection, a low-order X25519 part is refused at decapsulation. #[derive(Clone, PartialEq, Eq)] pub struct Ciphertext([u8; CIPHERTEXT_LEN]); impl Ciphertext { /// Parse a ciphertext. /// /// # Errors /// [`Error::InvalidLength`] if it is not 1120 bytes. pub fn from_bytes(bytes: &[u8]) -> Result { exact(Input::Ciphertext, bytes).map(|b| Self(*b)) } /// The 1120-byte encoding. #[must_use] pub fn as_bytes(&self) -> &[u8; CIPHERTEXT_LEN] { &self.0 } } impl fmt::Debug for Ciphertext { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Ciphertext").field("len", &CIPHERTEXT_LEN).finish_non_exhaustive() } } /// A hybrid secret key. Stored as its 32-byte seed plus the expanded keys; all zeroised on drop. pub struct SecretKey { seed: Zeroizing<[u8; SECRET_KEY_LEN]>, dk_m: MlKemDecapsulationKey, sk_x: StaticSecret, public: PublicKey, } impl SecretKey { /// Generate a new key pair from the caller's RNG. /// /// **`rng` must be the operating system's RNG** (`getrandom`, `OsRng`) or a CSPRNG seeded from it /// once per process; never a fixed, derived or configured seed. `CryptoRng` is only a marker: a /// CSPRNG with a constant seed satisfies it and makes this call fully deterministic (QA R2-04). pub fn generate(rng: &mut R) -> Self { let mut seed = Zeroizing::new([0u8; SECRET_KEY_LEN]); rng.fill_bytes(seed.as_mut_slice()); Self::expand(seed) } /// X-Wing `GenerateKeyPairDerand` (draft -11 §5.2.1): the key from a given 32-byte seed. /// **Hazmat** (feature `hazmat`), for tests: the caller's copy of `seed` is not wiped. Real /// code uses [`SecretKey::generate`], or [`SecretKey::from_bytes`] on a buffer it zeroises. #[cfg(feature = "hazmat")] #[must_use] pub fn from_seed(seed: [u8; SECRET_KEY_LEN]) -> Self { Self::expand(Zeroizing::new(seed)) } /// Parse a stored secret key (its 32-byte seed). /// /// # Errors /// [`Error::InvalidLength`] if it is not 32 bytes. Every 32-byte value is a valid key. pub fn from_bytes(bytes: &[u8]) -> Result { let seed: &[u8; SECRET_KEY_LEN] = exact(Input::SecretKey, bytes)?; Ok(Self::expand(Zeroizing::new(*seed))) } /// The 32-byte seed, for storing in Custos or Tessera. Handle with care. #[must_use] pub fn to_seed(&self) -> Zeroizing<[u8; SECRET_KEY_LEN]> { Zeroizing::new(*self.seed) } /// The matching public key. #[must_use] pub fn public_key(&self) -> &PublicKey { &self.public } /// X-Wing `Decapsulate` (draft -11 §5.5). **Hazmat** (feature `hazmat`), see the module docs. /// /// # Errors /// [`Error::NonContributory`] if the X25519 part of the ciphertext is a low-order point. A /// tampered ML-KEM part is not an error: ML-KEM's implicit rejection returns an unrelated secret. #[cfg(feature = "hazmat")] pub fn decapsulate(&self, ct: &Ciphertext) -> Result { self.decapsulate_inner(ct) } pub(crate) fn decapsulate_inner(&self, ct: &Ciphertext) -> Result { let ct_x: [u8; 32] = array::from_fn(|i| ct.0[ML_KEM_CIPHERTEXT_LEN + i]); let ss_x = self.sk_x.diffie_hellman(&X25519Public::from(ct_x)); if !ss_x.was_contributory() { return Err(Error::NonContributory); } let ct_m: [u8; ML_KEM_CIPHERTEXT_LEN] = array::from_fn(|i| ct.0[i]); let mut ss_m = self.dk_m.decapsulate(&Array::from(ct_m)); let ss_m_arr = as32(&ss_m); let ss = combiner(&ss_m_arr, ss_x.as_bytes(), &ct_x, self.public.pk_x.as_bytes()); ss_m.as_mut_slice().zeroize(); Ok(SharedSecret(Zeroizing::new(ss))) } /// `expandDecapsulationKey` (draft -11 §5.2): SHAKE256(seed) -> d || z || sk_X. fn expand(seed: Zeroizing<[u8; SECRET_KEY_LEN]>) -> Self { let mut expanded = Zeroizing::new([0u8; 96]); let mut xof = Shake256::default(); Update::update(&mut xof, seed.as_slice()); xof.finalize_xof().read(expanded.as_mut_slice()); let mut ml_seed = Seed::default(); ml_seed.as_mut_slice().copy_from_slice(&expanded[..64]); let dk_m = MlKemDecapsulationKey::from_seed(ml_seed); ml_seed.as_mut_slice().zeroize(); let mut sk_x_bytes = Zeroizing::new([0u8; 32]); sk_x_bytes.copy_from_slice(&expanded[64..]); let sk_x = StaticSecret::from(*sk_x_bytes); let pk_x = X25519Public::from(&sk_x); let pk_m = dk_m.encapsulation_key().clone(); let mut bytes = [0u8; PUBLIC_KEY_LEN]; bytes[..ML_KEM_PUBLIC_KEY_LEN].copy_from_slice(pk_m.to_bytes().as_slice()); bytes[ML_KEM_PUBLIC_KEY_LEN..].copy_from_slice(pk_x.as_bytes()); Self { seed, dk_m, sk_x, public: PublicKey { bytes, pk_m, pk_x } } } } impl fmt::Debug for SecretKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("SecretKey([redacted])") } } // `seed` is `Zeroizing`, and `ml-kem`'s and `x25519-dalek`'s key types wipe themselves on drop // (their `zeroize` features are enabled in Cargo.toml). impl ZeroizeOnDrop for SecretKey {} /// RFC 7748 encodes a u-coordinate as 32 little-endian bytes of a value below p = 2^255 - 19, with /// bit 255 clear; X25519 outputs (every honest public key) are always in that form. Decoders mask /// bit 255 and reduce mod p, so other encodings alias a canonical key: refuse them (QA R2-02). fn is_canonical_x25519(u: &[u8; 32]) -> bool { if u[31] & 0x80 != 0 { return false; } // With bit 255 clear, u >= p only for 2^255 - 19 ..= 2^255 - 1: ed..ff, then 30 x ff, then 7f. let at_least_p = u[31] == 0x7f && u[1..31].iter().all(|&b| b == 0xff) && u[0] >= 0xed; !at_least_p } /// Copy a 32-byte ML-KEM shared key into a stack array that is wiped on drop. fn as32(k: &ml_kem::SharedKey) -> Zeroizing<[u8; 32]> { let mut out = Zeroizing::new([0u8; 32]); out.copy_from_slice(k.as_slice()); out }