Files
arcanum/src/xwing.rs
T
mnovak 89b5329f06 feat: X-Wing (draft -11), mutual exchange, WireGuard PSK per epoch, sealed box
X-Wing is composed from ml-kem, x25519-dalek, sha3 and shake and matches the
draft's vectors. The PSK comes from a mutual exchange (each peer encapsulates
to the other, QA A-15) bound to the full transcript in Arcanum's own HKDF layer
(QA D-QA-1). Low-order X25519 values are refused. Deterministic entry points
sit behind the off-by-default hazmat feature, enabled only for the tests.
2026-11-25 07:38:55 +01:00

305 lines
12 KiB
Rust

//! 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.
//!
//! One deliberate difference from the draft: a low-order X25519 public key or ciphertext part is
//! refused with [`Error::NonContributory`]. Honest keys and ciphertexts are never low-order, so no
//! honest exchange and no official vector is affected (docs/01_arcanum.md).
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<MlKem768>;
type MlKemDecapsulationKey = ml_kem::DecapsulationKey<MlKem768>;
/// 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, for interoperating with other X-Wing users. Prefer [`crate::exchange`],
/// which binds the secret to the transcript and a context.
#[must_use]
pub fn as_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.
pub fn from_bytes(bytes: &[u8]) -> Result<Self, Error> {
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]);
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.
///
/// # Errors
/// [`Error::NonContributory`] if the X25519 part of the key is a low-order point.
pub fn encapsulate<R: CryptoRng + ?Sized>(&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::<u8, 32, _>(|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<Self, Error> {
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.
pub fn generate<R: CryptoRng + ?Sized>(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<Self, Error> {
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).
///
/// # 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.
pub fn decapsulate(&self, ct: &Ciphertext) -> Result<SharedSecret, Error> {
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 {}
/// 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
}