1use core::fmt;
16
17use quantaegis_core::{CryptoRng, Error, Kem, Result, SecretBytes, SharedSecret, Zeroize};
18use quantaegis_ml_kem::ml_kem_768;
19use quantaegis_sha3::{Sha3_256, Shake256};
20use x25519_dalek::{PublicKey as X25519PublicKey, StaticSecret as X25519Secret};
21
22pub const XWING_LABEL: [u8; 6] = [0x5c, 0x2e, 0x2f, 0x2f, 0x5e, 0x5c];
24
25pub const EK_LEN: usize = ml_kem_768::EK_LEN + 32;
27
28pub const DK_LEN: usize = 32;
30
31pub const CT_LEN: usize = ml_kem_768::CT_LEN + 32;
33
34pub const ENCAPS_SEED_LEN: usize = 64;
36
37pub const SHARED_SECRET_LEN: usize = 32;
39
40#[derive(Clone, Eq, PartialEq)]
42pub struct EncapsulationKey([u8; EK_LEN]);
43
44impl EncapsulationKey {
45 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
50 if bytes.len() != EK_LEN {
51 return Err(Error::InvalidLength {
52 expected: EK_LEN,
53 actual: bytes.len(),
54 });
55 }
56 let _ = ml_kem_768::EncapsulationKey::from_bytes(&bytes[..ml_kem_768::EK_LEN])?;
58
59 let mut out = [0u8; EK_LEN];
60 out.copy_from_slice(bytes);
61 Ok(Self(out))
62 }
63
64 #[inline]
66 pub const fn as_bytes(&self) -> &[u8; EK_LEN] {
67 &self.0
68 }
69}
70
71impl fmt::Debug for EncapsulationKey {
72 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
73 write!(f, "XWing::EncapsulationKey([{EK_LEN} bytes])")
74 }
75}
76
77pub struct DecapsulationKey(SecretBytes<DK_LEN>);
81
82impl DecapsulationKey {
83 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
85 if bytes.len() != DK_LEN {
86 return Err(Error::InvalidLength {
87 expected: DK_LEN,
88 actual: bytes.len(),
89 });
90 }
91 let mut out = [0u8; DK_LEN];
92 out.copy_from_slice(bytes);
93 Ok(Self(SecretBytes::new(out)))
94 }
95
96 #[inline]
98 pub const fn expose_bytes(&self) -> &[u8; DK_LEN] {
99 self.0.expose_secret()
100 }
101
102 pub fn encapsulation_key(&self) -> EncapsulationKey {
104 let (_sk_m, _sk_x, pk_m, pk_x) = expand_decapsulation_key(self.expose_bytes());
105 let mut ek = [0u8; EK_LEN];
106 ek[..ml_kem_768::EK_LEN].copy_from_slice(pk_m.as_bytes());
107 ek[ml_kem_768::EK_LEN..].copy_from_slice(pk_x.as_bytes());
108 EncapsulationKey(ek)
109 }
110}
111
112impl Zeroize for DecapsulationKey {
113 #[inline]
114 fn zeroize(&mut self) {
115 self.0.zeroize();
116 }
117}
118
119impl fmt::Debug for DecapsulationKey {
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 write!(f, "XWing::DecapsulationKey([REDACTED; {DK_LEN} bytes])")
122 }
123}
124
125#[derive(Clone, Eq, PartialEq)]
127pub struct Ciphertext([u8; CT_LEN]);
128
129impl Ciphertext {
130 pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
132 if bytes.len() != CT_LEN {
133 return Err(Error::InvalidLength {
134 expected: CT_LEN,
135 actual: bytes.len(),
136 });
137 }
138 let mut out = [0u8; CT_LEN];
139 out.copy_from_slice(bytes);
140 Ok(Self(out))
141 }
142
143 #[inline]
145 pub const fn as_bytes(&self) -> &[u8; CT_LEN] {
146 &self.0
147 }
148}
149
150impl fmt::Debug for Ciphertext {
151 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152 write!(f, "XWing::Ciphertext([{CT_LEN} bytes])")
153 }
154}
155
156fn expand_decapsulation_key(
160 sk: &[u8; DK_LEN],
161) -> (
162 ml_kem_768::DecapsulationKey,
163 X25519Secret,
164 ml_kem_768::EncapsulationKey,
165 X25519PublicKey,
166) {
167 let mut expanded = [0u8; 96];
168 Shake256::xof(sk, &mut expanded);
169
170 let mut d = [0u8; 32];
171 let mut z = [0u8; 32];
172 let mut sk_x_bytes = [0u8; 32];
173 d.copy_from_slice(&expanded[0..32]);
174 z.copy_from_slice(&expanded[32..64]);
175 sk_x_bytes.copy_from_slice(&expanded[64..96]);
176 expanded.zeroize();
177
178 let (pk_m, sk_m) = ml_kem_768::hazmat::keygen_internal(&d, &z);
179 let sk_x = X25519Secret::from(sk_x_bytes);
180 let pk_x = X25519PublicKey::from(&sk_x);
181
182 d.zeroize();
183 z.zeroize();
184 sk_x_bytes.zeroize();
185
186 (sk_m, sk_x, pk_m, pk_x)
187}
188
189fn combiner(ss_m: &[u8; 32], ss_x: &[u8; 32], ct_x: &[u8; 32], pk_x: &[u8; 32]) -> SharedSecret {
191 let mut hasher = Sha3_256::new();
192 hasher.update(ss_m);
193 hasher.update(ss_x);
194 hasher.update(ct_x);
195 hasher.update(pk_x);
196 hasher.update(&XWING_LABEL);
197 let ss = hasher.finalize();
198 SharedSecret::new(ss)
199}
200
201pub struct XWing;
203
204impl Kem for XWing {
205 type EncapsulationKey = EncapsulationKey;
206 type DecapsulationKey = DecapsulationKey;
207 type Ciphertext = Ciphertext;
208 type SharedSecret = SharedSecret;
209
210 fn keygen<R: CryptoRng + ?Sized>(
211 rng: &mut R,
212 ) -> Result<(Self::EncapsulationKey, Self::DecapsulationKey)> {
213 let mut sk = SecretBytes::new([0u8; DK_LEN]);
214 rng.try_fill_bytes(sk.expose_secret_mut())?;
215 Ok(keygen_derand_raw(sk.expose_secret()))
216 }
217
218 fn encaps<R: CryptoRng + ?Sized>(
219 ek: &Self::EncapsulationKey,
220 rng: &mut R,
221 ) -> Result<(Self::Ciphertext, Self::SharedSecret)> {
222 let mut eseed = SecretBytes::new([0u8; ENCAPS_SEED_LEN]);
223 rng.try_fill_bytes(eseed.expose_secret_mut())?;
224 encaps_derand_raw(ek, eseed.expose_secret())
225 }
226
227 fn decaps(dk: &Self::DecapsulationKey, ct: &Self::Ciphertext) -> Result<Self::SharedSecret> {
228 decaps_internal_raw(dk, ct)
229 }
230}
231
232fn keygen_derand_raw(sk: &[u8; DK_LEN]) -> (EncapsulationKey, DecapsulationKey) {
233 let (_sk_m, _sk_x, pk_m, pk_x) = expand_decapsulation_key(sk);
234 let mut ek = [0u8; EK_LEN];
235 ek[..ml_kem_768::EK_LEN].copy_from_slice(pk_m.as_bytes());
236 ek[ml_kem_768::EK_LEN..].copy_from_slice(pk_x.as_bytes());
237 (
238 EncapsulationKey(ek),
239 DecapsulationKey(SecretBytes::new(*sk)),
240 )
241}
242
243fn encaps_derand_raw(
244 ek: &EncapsulationKey,
245 eseed: &[u8; ENCAPS_SEED_LEN],
246) -> Result<(Ciphertext, SharedSecret)> {
247 let pk_m = ml_kem_768::EncapsulationKey::from_bytes(&ek.0[..ml_kem_768::EK_LEN])?;
248 let mut pk_x_bytes = [0u8; 32];
249 pk_x_bytes.copy_from_slice(&ek.0[ml_kem_768::EK_LEN..]);
250 let pk_x = X25519PublicKey::from(pk_x_bytes);
251
252 let mut m = [0u8; 32];
253 let mut ek_x_scalar = [0u8; 32];
254 m.copy_from_slice(&eseed[0..32]);
255 ek_x_scalar.copy_from_slice(&eseed[32..64]);
256
257 let (ct_m, mlkem_ss) = ml_kem_768::hazmat::encaps_internal(&pk_m, &m);
258 let eph_sk_x = X25519Secret::from(ek_x_scalar);
259 let ct_x = X25519PublicKey::from(&eph_sk_x);
260 let x25519_ss = eph_sk_x.diffie_hellman(&pk_x);
261
262 let ss = combiner(
263 mlkem_ss.expose_secret(),
264 x25519_ss.as_bytes(),
265 ct_x.as_bytes(),
266 pk_x.as_bytes(),
267 );
268
269 let mut ct = [0u8; CT_LEN];
270 ct[..ml_kem_768::CT_LEN].copy_from_slice(ct_m.as_bytes());
271 ct[ml_kem_768::CT_LEN..].copy_from_slice(ct_x.as_bytes());
272
273 m.zeroize();
274 ek_x_scalar.zeroize();
275
276 Ok((Ciphertext(ct), ss))
277}
278
279fn decaps_internal_raw(dk: &DecapsulationKey, ct: &Ciphertext) -> Result<SharedSecret> {
280 let (mlkem_dk, x25519_sk, _pk_m, pk_x) = expand_decapsulation_key(dk.expose_bytes());
281
282 let ct_m = ml_kem_768::Ciphertext::from_bytes(&ct.0[..ml_kem_768::CT_LEN])?;
283 let mut ct_x_bytes = [0u8; 32];
284 ct_x_bytes.copy_from_slice(&ct.0[ml_kem_768::CT_LEN..]);
285 let ct_x = X25519PublicKey::from(ct_x_bytes);
286
287 let mlkem_ss = ml_kem_768::hazmat::decaps_internal(&mlkem_dk, &ct_m);
288 let dh_secret = x25519_sk.diffie_hellman(&ct_x);
289
290 Ok(combiner(
291 mlkem_ss.expose_secret(),
292 dh_secret.as_bytes(),
293 ct_x.as_bytes(),
294 pk_x.as_bytes(),
295 ))
296}
297
298#[cfg(feature = "hazmat")]
303pub mod hazmat {
304 use quantaegis_core::{Result, SharedSecret};
305
306 use super::{
307 Ciphertext, DK_LEN, DecapsulationKey, ENCAPS_SEED_LEN, EncapsulationKey,
308 decaps_internal_raw, encaps_derand_raw, keygen_derand_raw,
309 };
310
311 pub fn keygen_derand(sk: &[u8; DK_LEN]) -> (EncapsulationKey, DecapsulationKey) {
313 keygen_derand_raw(sk)
314 }
315
316 pub fn encaps_derand(
320 ek: &EncapsulationKey,
321 eseed: &[u8; ENCAPS_SEED_LEN],
322 ) -> Result<(Ciphertext, SharedSecret)> {
323 encaps_derand_raw(ek, eseed)
324 }
325
326 pub fn decaps_internal(dk: &DecapsulationKey, ct: &Ciphertext) -> Result<SharedSecret> {
328 decaps_internal_raw(dk, ct)
329 }
330}
331
332#[cfg(test)]
333mod tests {
334 use super::*;
335 use quantaegis_sha3::Shake128;
336
337 struct TestRng(quantaegis_sha3::Shake128Reader);
338
339 impl CryptoRng for TestRng {
340 fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<()> {
341 self.0.squeeze(dest);
342 Ok(())
343 }
344 }
345
346 fn hex32(hex: &str) -> [u8; 32] {
347 assert_eq!(hex.len(), 64);
348 let b = hex.as_bytes();
349 let mut out = [0u8; 32];
350 for i in 0..32 {
351 let hi = match b[2 * i] {
352 b'0'..=b'9' => b[2 * i] - b'0',
353 b'a'..=b'f' => b[2 * i] - b'a' + 10,
354 _ => 0,
355 };
356 let lo = match b[2 * i + 1] {
357 b'0'..=b'9' => b[2 * i + 1] - b'0',
358 b'a'..=b'f' => b[2 * i + 1] - b'a' + 10,
359 _ => 0,
360 };
361 out[i] = (hi << 4) | lo;
362 }
363 out
364 }
365
366 #[test]
367 fn xwing_roundtrip_and_tamper_resistance() {
368 let mut xof = Shake128::new();
369 xof.update(b"quantaegis-hybrid-xwing-test");
370 let mut rng = TestRng(xof.finalize_xof());
371
372 let (ek, dk) = XWing::keygen(&mut rng)
373 .ok()
374 .unwrap_or_else(|| unreachable!());
375 assert_eq!(ek.as_bytes().len(), 1216);
376 assert_eq!(dk.expose_bytes().len(), 32);
377 assert_eq!(dk.encapsulation_key(), ek);
378
379 let (ct, ss_enc) = XWing::encaps(&ek, &mut rng)
380 .ok()
381 .unwrap_or_else(|| unreachable!());
382 assert_eq!(ct.as_bytes().len(), 1120);
383
384 let ss_dec = XWing::decaps(&dk, &ct)
385 .ok()
386 .unwrap_or_else(|| unreachable!());
387 assert!(ss_enc.ct_eq(&ss_dec).into_bool());
388
389 let mut tampered_mlkem = *ct.as_bytes();
391 tampered_mlkem[0] ^= 0x01;
392 let Ok(ct_bad_mlkem) = Ciphertext::from_bytes(&tampered_mlkem) else {
393 unreachable!();
394 };
395 let ss_bad_mlkem = XWing::decaps(&dk, &ct_bad_mlkem)
396 .ok()
397 .unwrap_or_else(|| unreachable!());
398 assert!(!ss_bad_mlkem.ct_eq(&ss_enc).into_bool());
399
400 let mut tampered_x25519 = *ct.as_bytes();
402 tampered_x25519[ml_kem_768::CT_LEN] ^= 0x01;
403 let Ok(ct_bad_x25519) = Ciphertext::from_bytes(&tampered_x25519) else {
404 unreachable!();
405 };
406 let ss_bad_x25519 = XWing::decaps(&dk, &ct_bad_x25519)
407 .ok()
408 .unwrap_or_else(|| unreachable!());
409 assert!(!ss_bad_x25519.ct_eq(&ss_enc).into_bool());
410 }
411
412 #[test]
413 fn xwing_rejects_malformed_ml_kem_public_key_modulus() {
414 let sk = [0x42u8; 32];
415 let (ek, _dk) = keygen_derand_raw(&sk);
416 let mut bad_ek = *ek.as_bytes();
417 bad_ek[0] = 0x01;
418 bad_ek[1] = (bad_ek[1] & 0xF0) | 0x0D; assert_eq!(
420 EncapsulationKey::from_bytes(&bad_ek),
421 Err(Error::InvalidEncapsulationKey)
422 );
423 }
424
425 #[test]
426 fn xwing_matches_independent_go_stdlib_cfrg_reference_kat() {
427 let sk = [0x7fu8; 32];
429 let eseed = [0x3eu8; 64];
430 let (ek, dk) = keygen_derand_raw(&sk);
431 let (ct, ss1) = encaps_derand_raw(&ek, &eseed)
432 .ok()
433 .unwrap_or_else(|| unreachable!());
434 let ss2 = decaps_internal_raw(&dk, &ct)
435 .ok()
436 .unwrap_or_else(|| unreachable!());
437
438 assert_eq!(
439 Sha3_256::digest(ek.as_bytes()),
440 hex32("6601edc8a6d170d6f4871c5aa5a4eaf9a49ce6b1c46bc8912d5d8beccbf7eeee")
441 );
442 assert_eq!(
443 Sha3_256::digest(ct.as_bytes()),
444 hex32("d9c8a42a28854ef7a4f7e3b3f4dbbed20582859c4f2c868135197a1af456fe47")
445 );
446 assert_eq!(
447 ss1.expose_secret(),
448 &hex32("619ad73cda73270d9444e15f2f1b433aad8c08f18507a7511ce64406226a3f09")
449 );
450 assert!(ss1.ct_eq(&ss2).into_bool());
451 }
452}