pqbox 1.1.0

Post-quantum crypto toolkit: hybrid ML-KEM-1024 + P-384 sealed boxes, composite ML-DSA-87 signatures, an opt-in paranoid suite adding Classic McEliece and SLH-DSA, AEAD, KDF, hashing and Argon2id
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
//! Hybrid key encapsulation, one construction per [`Suite`].
//!
//! | Suite | Components | Combiner |
//! |---|---|---|
//! | `xwing` (compat) | X-Wing: ML-KEM-768 + X25519 (`x-wing` crate) | X-Wing's own (IETF draft) |
//! | `pqbox-max` (default) | ML-KEM-1024 (`libcrux-ml-kem`, portable) + ECDH P-384 (`p384`) | `SHA3-256(ss_mlkem ‖ ss_p384 ‖ ct_p384 ‖ pk_p384 ‖ "pqbox/v1/kem-max")` |
//! | `pqbox-paranoid` | ML-KEM-1024 + Classic McEliece 8192128 (`classic-mceliece-rust`) + ECDH P-384 | `SHA3-256(ss_mlkem ‖ ss_mceliece ‖ ss_p384 ‖ ct_p384 ‖ pk_p384 ‖ SHA3-256(ct_mlkem) ‖ SHA3-256(ct_mceliece) ‖ "pqbox/v1/kem-paranoid")` |
//!
//! The `pqbox-max` and `pqbox-paranoid` combiners are modeled on X-Wing but are not
//! IETF-standardized. No post-quantum algorithm is implemented here: only the combiners.
//!
//! ML-KEM-1024 comes from Cryspen's formally verified `libcrux-ml-kem`, always through its
//! portable code (the module `mlkem1024::portable`, whatever features the build enables). The
//! ML-KEM-768 inside X-Wing comes from RustCrypto's `ml-kem`, which the `x-wing` crate is built on.
//! Both implement FIPS 203 exactly, so keys, ciphertexts and shared secrets do not depend on the
//! backend.
//!
//! Wire format (version 2), after the six-byte header (`kind`, `suite`):
//!
//! | Suite | Public key | Secret key | Ciphertext |
//! |---|---|---|---|
//! | `xwing` | X-Wing key (1216) | X-Wing seed (32) | X-Wing ciphertext (1120) |
//! | `pqbox-max` | ML-KEM-1024 ek (1568) ‖ P-384 point (97, uncompressed SEC1) | ML-KEM seed d‖z (64) ‖ P-384 scalar (48) | ML-KEM ct (1568) ‖ P-384 ephemeral point (97) |
//! | `pqbox-paranoid` | ML-KEM ek (1568) ‖ McEliece pk (1357824) ‖ P-384 point (97) | ML-KEM seed (64) ‖ McEliece sk (14120) ‖ P-384 scalar (48) ‖ McEliece pk (1357824) ‖ public key fingerprint (32) | ML-KEM ct (1568) ‖ McEliece ct (208) ‖ P-384 point (97) |
//!
//! The paranoid secret key embeds the McEliece public key, which cannot be cheaply recomputed
//! from the McEliece secret key, followed by the fingerprint of the whole public key
//! ([`PublicKey::fingerprint`]: SHA3-256 of its serialized form, every component included).
//! Parsing recomputes the ML-KEM encapsulation key from the seed and the P-384 point from the
//! scalar, rebuilds the public key with the embedded McEliece key and refuses the secret key
//! unless its fingerprint matches. A McEliece public key from another key pair, a corrupted one,
//! or an ML-KEM seed or P-384 scalar that does not belong with them is caught at parse time
//! instead of silently producing a key that cannot open what is sealed to it. (The McEliece
//! secret key and the ML-KEM implicit-rejection seed `z` do not show in the public key, so they
//! cannot be checked this way; a corrupted McEliece secret key makes `open` fail with
//! [`Error::Decrypt`].)

use libcrux_ml_kem::mlkem1024::{MlKem1024Ciphertext, MlKem1024PrivateKey, MlKem1024PublicKey, portable as mlkem1024};
use p384::elliptic_curve::Generate;
use p384::elliptic_curve::sec1::ToSec1Point;
use sha3::{Digest, Sha3_256};
use x_wing::{DecapsulationKeyRejectNonContrib, Decapsulator, KeyExport, TryDecapsulate};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};

use crate::format::{self, Kind, VERSION_2, fields};
use crate::{Error, Result, Rng, Suite, SuitePolicy};

/// Shared secret length (all suites).
pub const SHARED_SECRET_LEN: usize = 32;
/// ML-KEM-1024 encapsulation key length.
pub const MLKEM1024_EK_LEN: usize = 1568;
/// ML-KEM-1024 ciphertext length.
pub const MLKEM1024_CT_LEN: usize = 1568;
/// ML-KEM seed (d ‖ z) length.
pub const MLKEM_SEED_LEN: usize = 64;
/// Uncompressed SEC1 P-384 point length.
pub const P384_POINT_LEN: usize = 97;
/// P-384 scalar length.
pub const P384_SCALAR_LEN: usize = 48;
/// Classic McEliece 8192128 public key length.
pub const MCELIECE_PK_LEN: usize = 1_357_824;
/// Classic McEliece 8192128 secret key length.
pub const MCELIECE_SK_LEN: usize = 14_120;
/// Classic McEliece 8192128 ciphertext length.
pub const MCELIECE_CT_LEN: usize = 208;
#[cfg(feature = "paranoid")]
const _: () = assert!(
    MCELIECE_PK_LEN == classic_mceliece_rust::CRYPTO_PUBLICKEYBYTES
        && MCELIECE_SK_LEN == classic_mceliece_rust::CRYPTO_SECRETKEYBYTES
        && MCELIECE_CT_LEN == classic_mceliece_rust::CRYPTO_CIPHERTEXTBYTES
);
/// Public key fingerprint length (SHA3-256), as bound in a `pqbox-paranoid` secret key.
pub const FINGERPRINT_LEN: usize = 32;
/// Combiner label of `pqbox-max`.
pub const LABEL_MAX: &[u8] = b"pqbox/v1/kem-max";
/// Combiner label of `pqbox-paranoid`.
pub const LABEL_PARANOID: &[u8] = b"pqbox/v1/kem-paranoid";

/// Raw public key length for a suite.
#[must_use]
pub fn public_key_len(suite: Suite) -> usize {
    match suite {
        Suite::XWing => x_wing::ENCAPSULATION_KEY_SIZE,
        Suite::Max => MLKEM1024_EK_LEN + P384_POINT_LEN,
        #[cfg(feature = "paranoid")]
        Suite::Paranoid => MLKEM1024_EK_LEN + MCELIECE_PK_LEN + P384_POINT_LEN,
    }
}

/// Raw secret key length for a suite.
#[must_use]
pub fn secret_key_len(suite: Suite) -> usize {
    match suite {
        Suite::XWing => x_wing::DECAPSULATION_KEY_SIZE,
        Suite::Max => MLKEM_SEED_LEN + P384_SCALAR_LEN,
        #[cfg(feature = "paranoid")]
        Suite::Paranoid => MLKEM_SEED_LEN + MCELIECE_SK_LEN + P384_SCALAR_LEN + MCELIECE_PK_LEN + FINGERPRINT_LEN,
    }
}

/// Raw ciphertext length for a suite.
#[must_use]
pub fn ciphertext_len(suite: Suite) -> usize {
    match suite {
        Suite::XWing => x_wing::CIPHERTEXT_SIZE,
        Suite::Max => MLKEM1024_CT_LEN + P384_POINT_LEN,
        #[cfg(feature = "paranoid")]
        Suite::Paranoid => MLKEM1024_CT_LEN + MCELIECE_CT_LEN + P384_POINT_LEN,
    }
}

/// A 32-byte shared secret. Zeroized on drop; compared in constant time.
#[derive(Clone)]
pub struct SharedSecret(Zeroizing<[u8; SHARED_SECRET_LEN]>);

impl ZeroizeOnDrop for SharedSecret {}

impl SharedSecret {
    /// Copies a 32-byte secret into a new zeroizing buffer (the caller keeps the source wrapped
    /// in `Zeroizing` too, so neither copy outlives its use).
    fn copy_from(bytes: &[u8]) -> Result<Self> {
        let mut out = Zeroizing::new([0u8; SHARED_SECRET_LEN]);
        if bytes.len() != SHARED_SECRET_LEN {
            return Err(Error::InvalidLength("shared secret"));
        }
        out.copy_from_slice(bytes);
        Ok(Self(out))
    }

    /// The secret bytes.
    #[must_use]
    pub fn as_bytes(&self) -> &[u8; SHARED_SECRET_LEN] {
        &self.0
    }
}

impl PartialEq for SharedSecret {
    fn eq(&self, other: &Self) -> bool {
        crate::ct_eq(&*self.0, &*other.0)
    }
}
impl Eq for SharedSecret {}

impl core::fmt::Debug for SharedSecret {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str("SharedSecret(<redacted>)")
    }
}

type MlEk = MlKem1024PublicKey;

/// An ML-KEM-1024 decapsulation key (the expanded FIPS 203 `dk`, as libcrux keeps it), zeroized
/// on drop: libcrux's key types do not zeroize themselves.
struct MlDk(MlKem1024PrivateKey);

impl Zeroize for MlDk {
    fn zeroize(&mut self) {
        // `IndexMut<RangeFrom<usize>>` is libcrux's mutable view of the key bytes; `0..` cannot
        // panic.
        core::ops::IndexMut::index_mut(&mut self.0, 0..).zeroize();
    }
}

impl Drop for MlDk {
    fn drop(&mut self) {
        self.zeroize();
    }
}

impl ZeroizeOnDrop for MlDk {}

#[derive(Clone)]
enum PkInner {
    XWing(Box<x_wing::EncapsulationKey>),
    Max {
        ml: Box<MlEk>,
        ec: p384::PublicKey,
    },
    #[cfg(feature = "paranoid")]
    Paranoid {
        ml: Box<MlEk>,
        mce: Box<[u8; MCELIECE_PK_LEN]>,
        ec: p384::PublicKey,
    },
}

/// A KEM public (encapsulation) key.
#[derive(Clone)]
pub struct PublicKey {
    suite: Suite,
    inner: PkInner,
    raw: Vec<u8>,
}

impl PartialEq for PublicKey {
    fn eq(&self, other: &Self) -> bool {
        self.suite == other.suite && self.raw == other.raw
    }
}
impl Eq for PublicKey {}

impl core::fmt::Debug for PublicKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "kem::PublicKey({}, {} bytes)", self.suite, self.raw.len())
    }
}

/// SHA3-256 of a serialized public key (header included), from its raw body.
fn fingerprint(suite: Suite, raw: &[u8]) -> [u8; FINGERPRINT_LEN] {
    let header = format::Header::current(Kind::KemPublicKey, suite.id()).to_bytes();
    Sha3_256::new().chain_update(header).chain_update(raw).finalize().into()
}

/// Parses an ML-KEM-1024 encapsulation key, with the FIPS 203 modulus check (section 7.2).
fn mlkem_ek(raw: &[u8]) -> Result<Box<MlEk>> {
    let key = MlEk::try_from(raw).map_err(|_| Error::InvalidLength("ML-KEM-1024 public key"))?;
    if !mlkem1024::validate_public_key(&key) {
        return Err(Error::InvalidKey);
    }
    Ok(Box::new(key))
}

/// ML-KEM-1024 encapsulation. Draws the 32-byte message `m` from `rng` in one call, as RustCrypto's
/// `ml-kem` did, so a seeded RNG gives the same ciphertext as before.
fn mlkem_encapsulate<R: Rng + ?Sized>(ek: &MlEk, rng: &mut R) -> (MlKem1024Ciphertext, Zeroizing<[u8; 32]>) {
    let m = Zeroizing::new(crate::random::<32, R>(rng));
    let (ct, ss) = mlkem1024::encapsulate(ek, *m);
    (ct, Zeroizing::new(ss))
}

/// Parses an uncompressed SEC1 P-384 point: on the curve, not the identity.
pub(crate) fn p384_point(raw: &[u8]) -> Result<p384::PublicKey> {
    if raw.len() != P384_POINT_LEN || raw.first() != Some(&0x04) {
        return Err(Error::InvalidKey);
    }
    p384::PublicKey::from_sec1_bytes(raw).map_err(|_| Error::InvalidKey)
}

fn p384_encode(pk: &p384::PublicKey) -> Vec<u8> {
    pk.to_sec1_point(false).as_bytes().to_vec()
}

#[cfg(feature = "paranoid")]
fn boxed_array<const N: usize>(raw: &[u8], what: &'static str) -> Result<Box<[u8; N]>> {
    raw.to_vec()
        .into_boxed_slice()
        .try_into()
        .map_err(|_| Error::InvalidLength(what))
}

impl PublicKey {
    /// Parses a raw public key of `suite` (no header).
    ///
    /// # Errors
    /// [`Error::InvalidLength`] or [`Error::InvalidKey`] (including low-order X25519 points and
    /// P-384 points off the curve).
    pub fn from_raw(suite: Suite, raw: &[u8]) -> Result<Self> {
        let inner = match suite {
            Suite::XWing => {
                let [_, x] = fields(raw, [x_wing::ENCAPSULATION_KEY_SIZE - 32, 32], "KEM public key")?;
                let x: [u8; 32] = x.try_into().map_err(|_| Error::InvalidLength("KEM public key"))?;
                crate::hazmat::x25519_check_public(&x)?;
                PkInner::XWing(Box::new(
                    x_wing::EncapsulationKey::try_from(raw).map_err(|_| Error::InvalidKey)?,
                ))
            }
            Suite::Max => {
                let [ml, ec] = fields(raw, [MLKEM1024_EK_LEN, P384_POINT_LEN], "KEM public key")?;
                PkInner::Max {
                    ml: mlkem_ek(ml)?,
                    ec: p384_point(ec)?,
                }
            }
            #[cfg(feature = "paranoid")]
            Suite::Paranoid => {
                let [ml, mce, ec] = fields(
                    raw,
                    [MLKEM1024_EK_LEN, MCELIECE_PK_LEN, P384_POINT_LEN],
                    "KEM public key",
                )?;
                PkInner::Paranoid {
                    ml: mlkem_ek(ml)?,
                    mce: boxed_array(mce, "KEM public key")?,
                    ec: p384_point(ec)?,
                }
            }
        };
        Ok(Self {
            suite,
            inner,
            raw: raw.to_vec(),
        })
    }

    /// The suite.
    #[must_use]
    pub fn suite(&self) -> Suite {
        self.suite
    }

    /// The raw key (no header).
    #[must_use]
    pub fn as_raw(&self) -> &[u8] {
        &self.raw
    }

    /// SHA3-256 of the serialized key.
    #[must_use]
    pub fn fingerprint(&self) -> [u8; FINGERPRINT_LEN] {
        fingerprint(self.suite, &self.raw)
    }

    /// Serializes with the `PQB` header.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        format::encode(Kind::KemPublicKey, self.suite.id(), &[&self.raw])
    }

    /// Parses a serialized public key, accepting only the suites of [`SuitePolicy::DEFAULT`]
    /// (`pqbox-max`). Use [`Self::from_bytes_with_policy`] to accept other suites.
    ///
    /// # Errors
    /// Header errors, [`Error::UnknownSuite`], [`Error::SuiteNotAllowed`], [`Error::InvalidLength`] or [`Error::InvalidKey`].
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        Self::from_bytes_with_policy(data, SuitePolicy::DEFAULT)
    }

    /// Parses a serialized public key whose suite `policy` allows.
    ///
    /// # Errors
    /// Header errors, [`Error::UnknownSuite`], [`Error::SuiteNotAllowed`], [`Error::InvalidLength`] or [`Error::InvalidKey`].
    pub fn from_bytes_with_policy(data: &[u8], policy: SuitePolicy) -> Result<Self> {
        match format::expect(data, Kind::KemPublicKey)? {
            (h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
            (h, _) => Err(Error::UnsupportedVersion(h.version)),
        }
    }

    /// Encapsulates a fresh shared secret to this key.
    ///
    /// # Errors
    /// [`Error::InvalidKey`] if a classical share is degenerate (not reachable with a key that
    /// passed parsing).
    pub fn encapsulate<R: Rng + ?Sized>(&self, rng: &mut R) -> Result<(Ciphertext, SharedSecret)> {
        match &self.inner {
            PkInner::XWing(ek) => {
                let (ct, ss) = x_wing::Encapsulate::encapsulate_with_rng(&**ek, rng);
                let ss = Zeroizing::new(ss);
                Ok((
                    Ciphertext {
                        suite: self.suite,
                        raw: ct.to_vec(),
                    },
                    SharedSecret::copy_from(&ss)?,
                ))
            }
            PkInner::Max { ml, ec } => {
                let (ct_m, ss_m) = mlkem_encapsulate(ml, rng);
                let (ct_x, ss_x) = p384_encapsulate(ec, rng);
                let pk_x = p384_encode(ec);
                let ss = combine_max(&*ss_m, &ss_x, &ct_x, &pk_x);
                Ok((
                    Ciphertext {
                        suite: self.suite,
                        raw: [ct_m.as_ref(), &ct_x].concat(),
                    },
                    ss,
                ))
            }
            #[cfg(feature = "paranoid")]
            PkInner::Paranoid { ml, mce, ec } => {
                let (ct_m, ss_m) = mlkem_encapsulate(ml, rng);
                let mce_pk = classic_mceliece_rust::PublicKey::from(mce.clone());
                let (ct_c, ss_c) = classic_mceliece_rust::encapsulate_boxed(&mce_pk, &mut Rng06(rng));
                let (ct_x, ss_x) = p384_encapsulate(ec, rng);
                let pk_x = p384_encode(ec);
                let ss = combine_paranoid(
                    &*ss_m,
                    ss_c.as_array(),
                    &ss_x,
                    &ct_x,
                    &pk_x,
                    ct_m.as_ref(),
                    ct_c.as_array(),
                );
                Ok((
                    Ciphertext {
                        suite: self.suite,
                        raw: [ct_m.as_ref(), ct_c.as_array(), &ct_x].concat(),
                    },
                    ss,
                ))
            }
        }
    }
}

fn p384_encapsulate<R: Rng + ?Sized>(pk: &p384::PublicKey, rng: &mut R) -> (Vec<u8>, Zeroizing<[u8; 48]>) {
    let esk = <p384::ecdh::EphemeralSecret as Generate>::generate_from_rng(rng);
    let ct = p384_encode(&esk.public_key());
    let ss = esk.diffie_hellman(pk);
    let mut out = Zeroizing::new([0u8; 48]);
    out.copy_from_slice(ss.raw_secret_bytes());
    (ct, out)
}

fn combine_max(ss_m: &[u8], ss_x: &[u8; 48], ct_x: &[u8], pk_x: &[u8]) -> SharedSecret {
    let ss: [u8; 32] = Sha3_256::new()
        .chain_update(ss_m)
        .chain_update(ss_x)
        .chain_update(ct_x)
        .chain_update(pk_x)
        .chain_update(LABEL_MAX)
        .finalize()
        .into();
    SharedSecret(Zeroizing::new(ss))
}

#[cfg(feature = "paranoid")]
fn combine_paranoid(
    ss_m: &[u8],
    ss_c: &[u8],
    ss_x: &[u8; 48],
    ct_x: &[u8],
    pk_x: &[u8],
    ct_m: &[u8],
    ct_c: &[u8],
) -> SharedSecret {
    let ss: [u8; 32] = Sha3_256::new()
        .chain_update(ss_m)
        .chain_update(ss_c)
        .chain_update(ss_x)
        .chain_update(ct_x)
        .chain_update(pk_x)
        .chain_update(Sha3_256::digest(ct_m))
        .chain_update(Sha3_256::digest(ct_c))
        .chain_update(LABEL_PARANOID)
        .finalize()
        .into();
    SharedSecret(Zeroizing::new(ss))
}

/// A KEM ciphertext.
#[derive(Clone, PartialEq, Eq)]
pub struct Ciphertext {
    suite: Suite,
    raw: Vec<u8>,
}

impl core::fmt::Debug for Ciphertext {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "kem::Ciphertext({}, {} bytes)", self.suite, self.raw.len())
    }
}

impl Ciphertext {
    /// Wraps a raw ciphertext of `suite`.
    ///
    /// # Errors
    /// [`Error::InvalidLength`].
    pub fn from_raw(suite: Suite, raw: &[u8]) -> Result<Self> {
        if raw.len() != ciphertext_len(suite) {
            return Err(Error::InvalidLength("KEM ciphertext"));
        }
        Ok(Self {
            suite,
            raw: raw.to_vec(),
        })
    }

    /// The suite.
    #[must_use]
    pub fn suite(&self) -> Suite {
        self.suite
    }

    /// The raw ciphertext.
    #[must_use]
    pub fn as_raw(&self) -> &[u8] {
        &self.raw
    }

    /// Serializes with the `PQB` header.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        format::encode(Kind::KemCiphertext, self.suite.id(), &[&self.raw])
    }

    /// Parses a serialized ciphertext, accepting only the suites of [`SuitePolicy::DEFAULT`]
    /// (`pqbox-max`). Use [`Self::from_bytes_with_policy`] to accept other suites.
    ///
    /// # Errors
    /// Header errors, [`Error::UnknownSuite`], [`Error::SuiteNotAllowed`] or [`Error::InvalidLength`].
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        Self::from_bytes_with_policy(data, SuitePolicy::DEFAULT)
    }

    /// Parses a serialized ciphertext whose suite `policy` allows.
    ///
    /// # Errors
    /// Header errors, [`Error::UnknownSuite`], [`Error::SuiteNotAllowed`] or [`Error::InvalidLength`].
    pub fn from_bytes_with_policy(data: &[u8], policy: SuitePolicy) -> Result<Self> {
        match format::expect(data, Kind::KemCiphertext)? {
            (h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
            (h, _) => Err(Error::UnsupportedVersion(h.version)),
        }
    }
}

enum SkInner {
    XWing(Box<DecapsulationKeyRejectNonContrib>),
    Max {
        ml: Box<MlDk>,
        ec: p384::SecretKey,
    },
    #[cfg(feature = "paranoid")]
    Paranoid {
        ml: Box<MlDk>,
        mce: classic_mceliece_rust::SecretKey<'static>,
        ec: p384::SecretKey,
    },
}

/// A KEM secret (decapsulation) key.
///
/// Every component key zeroizes itself on drop, and so does the serialized form kept here.
pub struct SecretKey {
    inner: SkInner,
    secret: Zeroizing<Vec<u8>>,
    public: PublicKey,
}

impl ZeroizeOnDrop for SecretKey {}

impl core::fmt::Debug for SecretKey {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "kem::SecretKey({}, <redacted>)", self.public.suite)
    }
}

/// Adapts this crate's `rand_core` 0.10 RNG to the `rand_core` 0.6 traits that
/// `classic-mceliece-rust` expects. No randomness is transformed.
#[cfg(feature = "paranoid")]
struct Rng06<'a, R: ?Sized>(&'a mut R);

#[cfg(feature = "paranoid")]
impl<R: Rng + ?Sized> rand_core_06::RngCore for Rng06<'_, R> {
    fn next_u32(&mut self) -> u32 {
        rand_core::Rng::next_u32(self.0)
    }
    fn next_u64(&mut self) -> u64 {
        rand_core::Rng::next_u64(self.0)
    }
    fn fill_bytes(&mut self, dest: &mut [u8]) {
        rand_core::Rng::fill_bytes(self.0, dest);
    }
    fn try_fill_bytes(&mut self, dest: &mut [u8]) -> core::result::Result<(), rand_core_06::Error> {
        rand_core::Rng::fill_bytes(self.0, dest);
        Ok(())
    }
}
#[cfg(feature = "paranoid")]
impl<R: Rng + ?Sized> rand_core_06::CryptoRng for Rng06<'_, R> {}

/// Expands an ML-KEM-1024 seed `d ‖ z` (FIPS 203 `ML-KEM.KeyGen_internal`) into the
/// decapsulation key and the bytes of the encapsulation key.
fn mlkem_keypair(seed: &[u8]) -> Result<(Box<MlDk>, Vec<u8>)> {
    let seed: Zeroizing<[u8; MLKEM_SEED_LEN]> =
        Zeroizing::new(seed.try_into().map_err(|_| Error::InvalidLength("KEM secret key"))?);
    let (dk, ek) = mlkem1024::generate_key_pair(*seed).into_parts();
    Ok((Box::new(MlDk(dk)), ek.as_ref().to_vec()))
}

fn p384_secret(raw: &[u8]) -> Result<p384::SecretKey> {
    p384::SecretKey::from_slice(raw).map_err(|_| Error::InvalidKey)
}

impl SecretKey {
    /// Generates a fresh key of `suite`.
    ///
    /// `pqbox-paranoid` key generation runs Classic McEliece key generation, which takes
    /// hundreds of milliseconds, allocates a 1.3 MB public key and needs a few MiB of stack (more
    /// than the 2 MiB of a default spawned thread in some builds).
    ///
    /// # Errors
    /// Never in practice; kept fallible so that every suite shares one signature.
    pub fn generate<R: Rng + ?Sized>(suite: Suite, rng: &mut R) -> Result<Self> {
        match suite {
            Suite::XWing => {
                let seed = Zeroizing::new(crate::random::<32, R>(rng));
                Self::from_raw(suite, &seed[..])
            }
            Suite::Max => {
                let seed = Zeroizing::new(crate::random::<MLKEM_SEED_LEN, R>(rng));
                let ec = <p384::SecretKey as Generate>::generate_from_rng(rng);
                let ec_bytes = Zeroizing::new(ec.to_bytes());
                let raw = Zeroizing::new([&seed[..], &ec_bytes[..]].concat());
                Self::from_raw(suite, &raw)
            }
            #[cfg(feature = "paranoid")]
            Suite::Paranoid => {
                let seed = Zeroizing::new(crate::random::<MLKEM_SEED_LEN, R>(rng));
                let ec = <p384::SecretKey as Generate>::generate_from_rng(rng);
                let (mce_public, mce_secret) = classic_mceliece_rust::keypair_boxed(&mut Rng06(rng));
                let ec_bytes = Zeroizing::new(ec.to_bytes());
                let public = [
                    mlkem_keypair(&seed[..])?.1,
                    mce_public.as_array().to_vec(),
                    p384_encode(&ec.public_key()),
                ]
                .concat();
                let raw = Zeroizing::new(
                    [
                        &seed[..],
                        mce_secret.as_array(),
                        &ec_bytes[..],
                        mce_public.as_array(),
                        &fingerprint(suite, &public),
                    ]
                    .concat(),
                );
                Self::from_raw(suite, &raw)
            }
        }
    }

    /// Parses a raw secret key of `suite` (no header).
    ///
    /// # Errors
    /// [`Error::InvalidLength`] or [`Error::InvalidKey`] (for `pqbox-paranoid`, also when the
    /// public key fingerprint bound in the secret key does not match its components).
    pub fn from_raw(suite: Suite, raw: &[u8]) -> Result<Self> {
        let (inner, public_raw, bound_fingerprint): (SkInner, Vec<u8>, Option<&[u8]>) = match suite {
            Suite::XWing => {
                let seed: Zeroizing<[u8; 32]> =
                    Zeroizing::new(raw.try_into().map_err(|_| Error::InvalidLength("KEM secret key"))?);
                let dk = DecapsulationKeyRejectNonContrib::from(*seed);
                let pk = KeyExport::to_bytes(dk.encapsulation_key()).to_vec();
                (SkInner::XWing(Box::new(dk)), pk, None)
            }
            Suite::Max => {
                let [seed, ec] = fields(raw, [MLKEM_SEED_LEN, P384_SCALAR_LEN], "KEM secret key")?;
                let (ml, ml_pk) = mlkem_keypair(seed)?;
                let ec = p384_secret(ec)?;
                let pk = [ml_pk, p384_encode(&ec.public_key())].concat();
                (SkInner::Max { ml, ec }, pk, None)
            }
            #[cfg(feature = "paranoid")]
            Suite::Paranoid => {
                let [seed, mce_secret, ec, mce_public, bound] = fields(
                    raw,
                    [
                        MLKEM_SEED_LEN,
                        MCELIECE_SK_LEN,
                        P384_SCALAR_LEN,
                        MCELIECE_PK_LEN,
                        FINGERPRINT_LEN,
                    ],
                    "KEM secret key",
                )?;
                let (ml, ml_pk) = mlkem_keypair(seed)?;
                let ec = p384_secret(ec)?;
                let mce = classic_mceliece_rust::SecretKey::from(boxed_array::<MCELIECE_SK_LEN>(
                    mce_secret,
                    "KEM secret key",
                )?);
                let pk = [ml_pk, mce_public.to_vec(), p384_encode(&ec.public_key())].concat();
                (SkInner::Paranoid { ml, mce, ec }, pk, Some(bound))
            }
        };
        let public = PublicKey::from_raw(suite, &public_raw)?;
        if let Some(bound) = bound_fingerprint
            && !crate::ct_eq(&public.fingerprint(), bound)
        {
            return Err(Error::InvalidKey);
        }
        Ok(Self {
            inner,
            secret: Zeroizing::new(raw.to_vec()),
            public,
        })
    }

    /// The suite.
    #[must_use]
    pub fn suite(&self) -> Suite {
        self.public.suite
    }

    /// The matching public key.
    #[must_use]
    pub fn public_key(&self) -> &PublicKey {
        &self.public
    }

    /// The raw secret key (no header).
    #[must_use]
    pub fn as_raw(&self) -> &[u8] {
        &self.secret
    }

    /// Serializes with the `PQB` header. The buffer is zeroized on drop.
    #[must_use]
    pub fn to_bytes(&self) -> Zeroizing<Vec<u8>> {
        Zeroizing::new(format::encode(Kind::KemSecretKey, self.suite().id(), &[&self.secret]))
    }

    /// Parses a serialized secret key, accepting only the suites of [`SuitePolicy::DEFAULT`]
    /// (`pqbox-max`). Use [`Self::from_bytes_with_policy`] to accept other suites.
    ///
    /// # Errors
    /// Header errors, [`Error::UnknownSuite`], [`Error::SuiteNotAllowed`], [`Error::InvalidLength`] or [`Error::InvalidKey`].
    pub fn from_bytes(data: &[u8]) -> Result<Self> {
        Self::from_bytes_with_policy(data, SuitePolicy::DEFAULT)
    }

    /// Parses a serialized secret key whose suite `policy` allows.
    ///
    /// # Errors
    /// Header errors, [`Error::UnknownSuite`], [`Error::SuiteNotAllowed`], [`Error::InvalidLength`] or [`Error::InvalidKey`].
    pub fn from_bytes_with_policy(data: &[u8], policy: SuitePolicy) -> Result<Self> {
        match format::expect(data, Kind::KemSecretKey)? {
            (h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
            (h, _) => Err(Error::UnsupportedVersion(h.version)),
        }
    }

    /// Recovers the shared secret from a ciphertext.
    ///
    /// A ciphertext made for another key of the same suite yields an unrelated secret rather
    /// than an error (ML-KEM's implicit rejection); authenticate what you derive from it.
    ///
    /// # Errors
    /// [`Error::SuiteMismatch`] for a ciphertext of another suite, [`Error::Decrypt`] for a
    /// degenerate classical share (non-contributory X25519, invalid P-384 point).
    pub fn decapsulate(&self, ct: &Ciphertext) -> Result<SharedSecret> {
        if ct.suite != self.suite() {
            return Err(Error::SuiteMismatch {
                expected: self.suite().name(),
                found: ct.suite.name(),
            });
        }
        match &self.inner {
            SkInner::XWing(dk) => {
                let c = x_wing::Ciphertext::try_from(ct.raw.as_slice())
                    .map_err(|_| Error::InvalidLength("KEM ciphertext"))?;
                let ss = Zeroizing::new(dk.try_decapsulate(&c).map_err(|_| Error::Decrypt)?);
                SharedSecret::copy_from(&ss)
            }
            SkInner::Max { ml, ec } => {
                let [ct_m, ct_x] = fields(&ct.raw, [MLKEM1024_CT_LEN, P384_POINT_LEN], "KEM ciphertext")?;
                let ss_m = mlkem_decapsulate(ml, ct_m)?;
                let ss_x = p384_decapsulate(ec, ct_x)?;
                let pk_x = p384_encode(&ec.public_key());
                Ok(combine_max(&*ss_m, &ss_x, ct_x, &pk_x))
            }
            #[cfg(feature = "paranoid")]
            SkInner::Paranoid { ml, mce, ec } => {
                let [ct_m, ct_c, ct_x] = fields(
                    &ct.raw,
                    [MLKEM1024_CT_LEN, MCELIECE_CT_LEN, P384_POINT_LEN],
                    "KEM ciphertext",
                )?;
                let ss_m = mlkem_decapsulate(ml, ct_m)?;
                let ct_c_arr: [u8; MCELIECE_CT_LEN] =
                    ct_c.try_into().map_err(|_| Error::InvalidLength("KEM ciphertext"))?;
                let ss_c = classic_mceliece_rust::decapsulate_boxed(&ct_c_arr.into(), mce);
                let ss_x = p384_decapsulate(ec, ct_x)?;
                let pk_x = p384_encode(&ec.public_key());
                Ok(combine_paranoid(
                    &*ss_m,
                    ss_c.as_array(),
                    &ss_x,
                    ct_x,
                    &pk_x,
                    ct_m,
                    ct_c,
                ))
            }
        }
    }
}

fn mlkem_decapsulate(dk: &MlDk, ct: &[u8]) -> Result<Zeroizing<[u8; 32]>> {
    let ct = MlKem1024Ciphertext::try_from(ct).map_err(|_| Error::InvalidLength("KEM ciphertext"))?;
    Ok(Zeroizing::new(mlkem1024::decapsulate(&dk.0, &ct)))
}

fn p384_decapsulate(sk: &p384::SecretKey, ct: &[u8]) -> Result<Zeroizing<[u8; 48]>> {
    let point = p384_point(ct).map_err(|_| Error::Decrypt)?;
    let ss = sk.diffie_hellman(&point);
    let mut out = Zeroizing::new([0u8; 48]);
    out.copy_from_slice(ss.raw_secret_bytes());
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::test_util::rng;

    fn suites() -> impl Iterator<Item = Suite> {
        Suite::ALL.into_iter()
    }

    #[test]
    fn round_trip_every_suite() {
        let mut rng = rng();
        for suite in suites() {
            let sk = SecretKey::generate(suite, &mut rng).unwrap();
            assert_eq!(sk.as_raw().len(), secret_key_len(suite));
            assert_eq!(sk.public_key().as_raw().len(), public_key_len(suite));
            let (ct, ss) = sk.public_key().encapsulate(&mut rng).unwrap();
            assert_eq!(ct.as_raw().len(), ciphertext_len(suite));
            assert_eq!(sk.decapsulate(&ct).unwrap(), ss);
            let all = SuitePolicy::ALL;
            let sk2 = SecretKey::from_bytes_with_policy(&sk.to_bytes(), all).unwrap();
            assert_eq!(sk2.public_key(), sk.public_key());
            let pk = PublicKey::from_bytes_with_policy(&sk.public_key().to_bytes(), all).unwrap();
            assert_eq!(&pk, sk.public_key());
            assert_eq!(Ciphertext::from_bytes_with_policy(&ct.to_bytes(), all).unwrap(), ct);
            // The default policy accepts pqbox-max only.
            let default = PublicKey::from_bytes(&sk.public_key().to_bytes());
            if suite == Suite::Max {
                assert_eq!(default.unwrap(), pk);
            } else {
                assert_eq!(default.unwrap_err(), Error::SuiteNotAllowed(suite.name()));
                assert_eq!(
                    SecretKey::from_bytes(&sk.to_bytes()).unwrap_err(),
                    Error::SuiteNotAllowed(suite.name())
                );
                assert_eq!(
                    Ciphertext::from_bytes(&ct.to_bytes()).unwrap_err(),
                    Error::SuiteNotAllowed(suite.name())
                );
            }
        }
    }

    #[test]
    fn wrong_key_gives_unrelated_secret() {
        let mut rng = rng();
        for suite in suites() {
            let a = SecretKey::generate(suite, &mut rng).unwrap();
            let b = SecretKey::generate(suite, &mut rng).unwrap();
            let (ct, ss) = a.public_key().encapsulate(&mut rng).unwrap();
            assert_ne!(b.decapsulate(&ct).unwrap(), ss);
        }
    }

    #[test]
    fn cross_suite_is_rejected() {
        let mut rng = rng();
        let x = SecretKey::generate(Suite::XWing, &mut rng).unwrap();
        let m = SecretKey::generate(Suite::Max, &mut rng).unwrap();
        let (ct, _) = x.public_key().encapsulate(&mut rng).unwrap();
        assert!(matches!(m.decapsulate(&ct), Err(Error::SuiteMismatch { .. })));
        // A serialized key relabeled with another suite fails to parse (lengths differ).
        let mut relabeled = m.public_key().to_bytes();
        relabeled[5] = Suite::XWing.id();
        assert_eq!(
            PublicKey::from_bytes_with_policy(&relabeled, SuitePolicy::ALL),
            Err(Error::InvalidLength("KEM public key"))
        );
    }

    /// Regression: the McEliece public key embedded in a `pqbox-paranoid` secret key was not
    /// checked, so a key carrying another key pair's McEliece public key parsed fine and then
    /// could not open anything sealed to its own public key.
    #[cfg(feature = "paranoid")]
    #[test]
    fn paranoid_secret_key_binds_its_public_key() {
        let mut rng = rng();
        let a = SecretKey::generate(Suite::Paranoid, &mut rng).unwrap();
        let b = SecretKey::generate(Suite::Paranoid, &mut rng).unwrap();
        let start = MLKEM_SEED_LEN + MCELIECE_SK_LEN + P384_SCALAR_LEN;
        let mce = start..start + MCELIECE_PK_LEN;
        assert_eq!(a.as_raw().len(), mce.end + FINGERPRINT_LEN);
        assert_eq!(&a.as_raw()[mce.end..], a.public_key().fingerprint());

        // b's McEliece public key in a's secret key (the reviewer's "franken" key).
        let mut franken = a.as_raw().to_vec();
        franken[mce.clone()].copy_from_slice(&b.as_raw()[mce.clone()]);
        assert_eq!(
            SecretKey::from_raw(Suite::Paranoid, &franken).unwrap_err(),
            Error::InvalidKey
        );

        // One flipped bit in the embedded McEliece key, the ML-KEM seed's `d` half (its `z` half
        // only drives implicit rejection and does not show in the public key), the P-384 scalar
        // or the fingerprint itself.
        for pos in [
            mce.start,
            mce.start + MCELIECE_PK_LEN / 2,
            mce.end - 1,
            0,
            31,
            start - 1,
            mce.end,
            a.as_raw().len() - 1,
        ] {
            let mut raw = a.as_raw().to_vec();
            raw[pos] ^= 1;
            assert!(
                matches!(SecretKey::from_raw(Suite::Paranoid, &raw), Err(Error::InvalidKey)),
                "flip at {pos} accepted"
            );
        }
        assert_eq!(
            SecretKey::from_raw(Suite::Paranoid, a.as_raw()).unwrap().public_key(),
            a.public_key()
        );
    }

    #[test]
    fn debug_redacts_secrets() {
        let mut rng = rng();
        let sk = SecretKey::generate(Suite::Max, &mut rng).unwrap();
        let dbg = format!("{sk:?}");
        assert!(dbg.contains("redacted"));
        let hex = crate::test_util::to_hex(&sk.as_raw()[..8]);
        assert!(!dbg.contains(&hex));
        let (_, ss) = sk.public_key().encapsulate(&mut rng).unwrap();
        assert_eq!(format!("{ss:?}"), "SharedSecret(<redacted>)");
    }

    #[test]
    fn secret_types_zeroize_on_drop() {
        fn assert_zod<T: ZeroizeOnDrop>() {}
        assert_zod::<SecretKey>();
        assert_zod::<SharedSecret>();
        assert_zod::<MlDk>();
        assert_zod::<p384::SecretKey>();
        assert_zod::<x_wing::DecapsulationKey>();
        #[cfg(feature = "paranoid")]
        assert_zod::<classic_mceliece_rust::SecretKey<'static>>();
    }

    /// libcrux's decapsulation key does not zeroize itself; the `MlDk` wrapper wipes every byte.
    #[test]
    fn mlkem_decapsulation_key_zeroizes() {
        let (mut dk, _) = mlkem_keypair(&[7u8; MLKEM_SEED_LEN]).unwrap();
        assert!(dk.0.as_slice().iter().any(|&b| b != 0));
        dk.zeroize();
        assert!(dk.0.as_slice().iter().all(|&b| b == 0));
    }
}