pqbox 1.0.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
//! Composite (hybrid) signatures, one construction per [`Suite`]. Every component signature must
//! verify.
//!
//! | Suite | Components | Label |
//! |---|---|---|
//! | `xwing` (compat) | ML-DSA-65 + Ed25519 | `COMPSIG-MLDSA65-Ed25519-SHA512` |
//! | `pqbox-max` (default) | ML-DSA-87 + ECDSA P-384 (SHA-384) | `COMPSIG-MLDSA87-ECDSA-P384-SHA512` |
//! | `pqbox-paranoid` | ML-DSA-87 + SLH-DSA-SHAKE-256s + ECDSA P-384 (SHA-384) | `pqbox/v1/COMPSIG-MLDSA87-SLHDSA-SHAKE256s-ECDSA-P384-SHA512` |
//!
//! The construction follows the IETF composite ML-DSA draft
//! (draft-ietf-lamps-pq-composite-sigs-19, section 3.2):
//!
//! ```text
//! ctx = "pqbox/v1/sig" || SHA3-256(serialized public key)
//! M'  = "CompositeAlgorithmSignatures2025" || Label || len(ctx) || ctx || SHA-512(M)
//! sig = ML-DSA.Sign(M', ctx = Label) [|| SLH-DSA.Sign(M', ctx = Label)] || Trad.Sign(M')
//! ```
//!
//! Deviations from the draft, all deliberate:
//! - keys and signatures use pqbox's own header and fixed-length encodings, not ASN.1/X.509;
//! - the ECDSA signature is the fixed 96-byte `r || s` (IEEE P1363) form, not DER;
//! - the application context always binds the signer's public key fingerprint;
//! - `pqbox-paranoid` has no draft counterpart; it adds SLH-DSA with a pqbox-specific label;
//! - ML-DSA and SLH-DSA use hedged (randomized) signing; ECDSA uses RFC 6979;
//! - the ECDSA `s` must be in the lower half of the group order (signing normalizes it, and
//!   verification refuses the high-`s` twin), and Ed25519 is verified strictly.
//!
//! Composite signatures are strongly unforgeable (SUF-CMA): besides being unable to sign a new
//! message, an attacker cannot turn a valid signature into a second valid signature of the same
//! message. A composite signature is only as non-malleable as its most malleable component, so
//! every component is held to a unique valid encoding: ML-DSA (FIPS 204) and SLH-DSA
//! (FIPS 205) are designed to be strongly unforgeable, Ed25519 is verified with
//! `verify_strict` (canonical `S`, no small-order points), and ECDSA, which is malleable through
//! `s -> n - s`, is restricted to low-`s` signatures.
//!
//! Wire format (version 2), after the six-byte header:
//!
//! | Suite | Public key | Secret key | Signature |
//! |---|---|---|---|
//! | `xwing` | ML-DSA-65 pk (1952) ‖ Ed25519 pk (32) | ML-DSA seed ξ (32) ‖ Ed25519 seed (32) | ML-DSA-65 sig (3309) ‖ Ed25519 sig (64) |
//! | `pqbox-max` | ML-DSA-87 pk (2592) ‖ P-384 point (97) | ξ (32) ‖ P-384 scalar (48) | ML-DSA-87 sig (4627) ‖ ECDSA r‖s (96) |
//! | `pqbox-paranoid` | ML-DSA-87 pk (2592) ‖ SLH-DSA pk (64) ‖ P-384 point (97) | ξ (32) ‖ SLH-DSA sk (128) ‖ P-384 scalar (48) | ML-DSA-87 sig (4627) ‖ SLH-DSA sig (29792) ‖ ECDSA r‖s (96) |

use ml_dsa::{
    EncodedVerifyingKey, MlDsa65, MlDsa87, MlDsaParams, SigningKey as MlSigningKey, VerifyingKey as MlVerifyingKey,
};
use p384::ecdsa::signature::{Signer as _, Verifier as _};
use sha2::Sha512;
use sha3::{Digest, Sha3_256};
#[cfg(feature = "paranoid")]
use slh_dsa::Shake256s;
use zeroize::{ZeroizeOnDrop, Zeroizing};

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

/// Prefix of every message representative (composite ML-DSA draft).
pub const PREFIX: &[u8] = b"CompositeAlgorithmSignatures2025";
/// Application context label; the signer's fingerprint follows it in `ctx`.
pub const CONTEXT: &[u8] = b"pqbox/v1/sig";

const MLDSA65_PK: usize = 1952;
const MLDSA65_SIG: usize = 3309;
const MLDSA87_PK: usize = 2592;
const MLDSA87_SIG: usize = 4627;
const MLDSA_SEED: usize = 32;
#[cfg(feature = "paranoid")]
const SLH_PK: usize = 64;
#[cfg(feature = "paranoid")]
const SLH_SK: usize = 128;
#[cfg(feature = "paranoid")]
const SLH_SIG: usize = 29792;
const ED_PK: usize = 32;
const ED_SK: usize = 32;
const ED_SIG: usize = 64;
const P384_PK: usize = 97;
const P384_SK: usize = 48;
const P384_SIG: usize = 96;

/// The composite label of a suite.
#[must_use]
pub fn label(suite: Suite) -> &'static [u8] {
    match suite {
        Suite::XWing => b"COMPSIG-MLDSA65-Ed25519-SHA512",
        Suite::Max => b"COMPSIG-MLDSA87-ECDSA-P384-SHA512",
        #[cfg(feature = "paranoid")]
        Suite::Paranoid => b"pqbox/v1/COMPSIG-MLDSA87-SLHDSA-SHAKE256s-ECDSA-P384-SHA512",
    }
}

/// Field lengths `[ml-dsa, slh-dsa, classical]` of a public key.
fn pk_lens(suite: Suite) -> [usize; 3] {
    match suite {
        Suite::XWing => [MLDSA65_PK, 0, ED_PK],
        Suite::Max => [MLDSA87_PK, 0, P384_PK],
        #[cfg(feature = "paranoid")]
        Suite::Paranoid => [MLDSA87_PK, SLH_PK, P384_PK],
    }
}

fn sk_lens(suite: Suite) -> [usize; 3] {
    match suite {
        Suite::XWing => [MLDSA_SEED, 0, ED_SK],
        Suite::Max => [MLDSA_SEED, 0, P384_SK],
        #[cfg(feature = "paranoid")]
        Suite::Paranoid => [MLDSA_SEED, SLH_SK, P384_SK],
    }
}

fn sig_lens(suite: Suite) -> [usize; 3] {
    match suite {
        Suite::XWing => [MLDSA65_SIG, 0, ED_SIG],
        Suite::Max => [MLDSA87_SIG, 0, P384_SIG],
        #[cfg(feature = "paranoid")]
        Suite::Paranoid => [MLDSA87_SIG, SLH_SIG, P384_SIG],
    }
}

/// Raw public key length for a suite.
#[must_use]
pub fn public_key_len(suite: Suite) -> usize {
    pk_lens(suite).iter().sum()
}

/// Raw secret key length for a suite.
#[must_use]
pub fn secret_key_len(suite: Suite) -> usize {
    sk_lens(suite).iter().sum()
}

/// Raw signature length for a suite.
#[must_use]
pub fn signature_len(suite: Suite) -> usize {
    sig_lens(suite).iter().sum()
}

#[derive(Clone)]
enum MlVk {
    L65(Box<MlVerifyingKey<MlDsa65>>),
    L87(Box<MlVerifyingKey<MlDsa87>>),
}

#[derive(Clone)]
enum TradVk {
    Ed25519([u8; ED_PK]),
    P384(p384::ecdsa::VerifyingKey),
}

/// A composite signing public key.
#[derive(Clone)]
pub struct PublicKey {
    suite: Suite,
    ml: MlVk,
    #[cfg(feature = "paranoid")]
    slh: Option<Box<slh_dsa::VerifyingKey<Shake256s>>>,
    trad: TradVk,
    raw: Vec<u8>,
    fingerprint: [u8; 32],
}

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 {
        let fp = self.fingerprint.iter().take(8).fold(String::new(), |mut acc, b| {
            let _ = core::fmt::Write::write_fmt(&mut acc, format_args!("{b:02x}"));
            acc
        });
        write!(f, "sign::PublicKey({}, {fp}..)", self.suite)
    }
}

pub(crate) fn p384_vk(raw: &[u8]) -> Result<p384::ecdsa::VerifyingKey> {
    if raw.len() != P384_PK || raw.first() != Some(&0x04) {
        return Err(Error::InvalidKey);
    }
    p384::ecdsa::VerifyingKey::from_sec1_bytes(raw).map_err(|_| Error::InvalidKey)
}

impl PublicKey {
    /// Parses a raw public key of `suite` (no header).
    ///
    /// # Errors
    /// [`Error::InvalidLength`] or [`Error::InvalidKey`].
    pub fn from_raw(suite: Suite, raw: &[u8]) -> Result<Self> {
        let [ml_raw, slh_raw, trad_raw] = fields(raw, pk_lens(suite), "signing public key")?;
        // `xwing` uses ML-DSA-65 and Ed25519; `pqbox-max` and `pqbox-paranoid` ML-DSA-87 and P-384.
        let ml = if suite == Suite::XWing {
            MlVk::L65(Box::new(MlVerifyingKey::decode(
                &EncodedVerifyingKey::<MlDsa65>::try_from(ml_raw).map_err(|_| Error::InvalidKey)?,
            )))
        } else {
            MlVk::L87(Box::new(MlVerifyingKey::decode(
                &EncodedVerifyingKey::<MlDsa87>::try_from(ml_raw).map_err(|_| Error::InvalidKey)?,
            )))
        };
        #[cfg(feature = "paranoid")]
        let slh = match suite {
            Suite::Paranoid => Some(Box::new(
                slh_dsa::VerifyingKey::<Shake256s>::try_from(slh_raw).map_err(|_| Error::InvalidKey)?,
            )),
            Suite::XWing | Suite::Max => None,
        };
        #[cfg(not(feature = "paranoid"))]
        let _ = slh_raw;
        let trad = if suite == Suite::XWing {
            let pk: [u8; ED_PK] = trad_raw.try_into().map_err(|_| Error::InvalidKey)?;
            let vk = ed25519_dalek::VerifyingKey::from_bytes(&pk).map_err(|_| Error::InvalidKey)?;
            // Small-order keys would let one signature verify for many messages.
            if vk.is_weak() {
                return Err(Error::InvalidKey);
            }
            TradVk::Ed25519(pk)
        } else {
            TradVk::P384(p384_vk(trad_raw)?)
        };
        let header = format::Header::current(Kind::SignPublicKey, suite.id()).to_bytes();
        let fingerprint = Sha3_256::new().chain_update(header).chain_update(raw).finalize().into();
        Ok(Self {
            suite,
            ml,
            #[cfg(feature = "paranoid")]
            slh,
            trad,
            raw: raw.to_vec(),
            fingerprint,
        })
    }

    /// 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, bound into every signature.
    #[must_use]
    pub fn fingerprint(&self) -> &[u8; 32] {
        &self.fingerprint
    }

    /// Serializes with the `PQB` header.
    #[must_use]
    pub fn to_bytes(&self) -> Vec<u8> {
        format::encode(Kind::SignPublicKey, 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::SignPublicKey)? {
            (h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
            (h, _) => Err(Error::UnsupportedVersion(h.version)),
        }
    }

    /// Verifies a composite signature: every component must verify.
    ///
    /// # Errors
    /// [`Error::SuiteMismatch`] for a signature of another suite, [`Error::BadSignature`] if any
    /// component fails.
    pub fn verify(&self, message: &[u8], signature: &Signature) -> Result<()> {
        if signature.suite != self.suite {
            return Err(Error::SuiteMismatch {
                expected: self.suite.name(),
                found: signature.suite.name(),
            });
        }
        let [ml_sig, slh_sig, trad_sig] = fields(&signature.raw, sig_lens(self.suite), "signature")?;
        let lbl = label(self.suite);
        let m = message_representative(self.suite, &self.fingerprint, message);

        let ml_ok = match &self.ml {
            MlVk::L65(vk) => mldsa_verify(vk, &m, lbl, ml_sig),
            MlVk::L87(vk) => mldsa_verify(vk, &m, lbl, ml_sig),
        };
        #[cfg(feature = "paranoid")]
        let slh_ok = match &self.slh {
            Some(vk) => slh_dsa::Signature::<Shake256s>::try_from(slh_sig)
                .is_ok_and(|s| vk.try_verify_with_context(&m, lbl, &s).is_ok()),
            None => true,
        };
        // Without the feature no suite has an SLH-DSA component, so the field is always empty.
        #[cfg(not(feature = "paranoid"))]
        let slh_ok = slh_sig.is_empty();
        let trad_ok = match &self.trad {
            TradVk::Ed25519(pk) => {
                <[u8; ED_SIG]>::try_from(trad_sig).is_ok_and(|s| crate::hazmat::ed25519_verify(pk, &m, &s))
            }
            TradVk::P384(vk) => ecdsa_p384_verify(vk, &m, trad_sig),
        };
        // Every component is always evaluated: no early exit on the first failure.
        if ml_ok & slh_ok & trad_ok {
            Ok(())
        } else {
            Err(Error::BadSignature)
        }
    }
}

/// ML-DSA signing as the composite signatures run it: FIPS 204 ML-DSA.Sign with context `ctx`,
/// hedged with 32 bytes of `rnd` drawn from `rng` (an all-zero `rnd` gives the deterministic
/// variant). Returns the encoded signature.
pub(crate) fn mldsa_sign<P: MlDsaParams, R: Rng + ?Sized>(
    sk: &MlSigningKey<P>,
    message: &[u8],
    ctx: &[u8],
    rng: &mut R,
) -> Result<Vec<u8>> {
    Ok(sk
        .expanded_key()
        .sign_randomized(message, ctx, rng)
        .map_err(|_| Error::InvalidParams("ML-DSA signing failed"))?
        .encode()
        .to_vec())
}

/// ML-DSA verification as the composite signatures run it: FIPS 204 ML-DSA.Verify with context
/// `ctx` over an encoded signature of the exact length.
pub(crate) fn mldsa_verify<P: MlDsaParams>(
    vk: &MlVerifyingKey<P>,
    message: &[u8],
    ctx: &[u8],
    signature: &[u8],
) -> bool {
    ml_dsa::Signature::<P>::try_from(signature).is_ok_and(|s| vk.verify_with_context(message, ctx, &s))
}

/// The encoded ML-DSA public key of the key pair derived from the seed `xi`.
pub(crate) fn mldsa_public_key<P: MlDsaParams>(sk: &MlSigningKey<P>) -> Vec<u8> {
    sk.expanded_key().verifying_key().encode().to_vec()
}

/// ECDSA P-384 (SHA-384) verification as the composite signatures run it: a fixed 96-byte
/// `r || s` signature whose `s` is in the lower half of the group order. ECDSA itself accepts
/// both `(r, s)` and `(r, n - s)`; refusing the high-`s` twin makes the signature non-malleable,
/// which the composite needs to be strongly unforgeable.
pub(crate) fn ecdsa_p384_verify(vk: &p384::ecdsa::VerifyingKey, message: &[u8], signature: &[u8]) -> bool {
    p384::ecdsa::Signature::from_slice(signature).is_ok_and(|s| s.normalize_s() == s && vk.verify(message, &s).is_ok())
}

/// `M' = Prefix || Label || len(ctx) || ctx || SHA-512(M)` with `ctx = CONTEXT || fingerprint`.
fn message_representative(suite: Suite, fingerprint: &[u8; 32], message: &[u8]) -> Vec<u8> {
    let lbl = label(suite);
    let ph = Sha512::digest(message);
    let mut m = Vec::with_capacity(PREFIX.len() + lbl.len() + 1 + CONTEXT.len() + 32 + ph.len());
    m.extend_from_slice(PREFIX);
    m.extend_from_slice(lbl);
    // CONTEXT (12 bytes) + fingerprint (32 bytes) = 44, well below 256.
    m.push(44);
    m.extend_from_slice(CONTEXT);
    m.extend_from_slice(fingerprint);
    m.extend_from_slice(&ph);
    m
}

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

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

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

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

    /// The raw signature (no header).
    #[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::Signature, self.suite.id(), &[&self.raw])
    }

    /// Parses a serialized signature, 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 signature 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::Signature)? {
            (h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
            (h, _) => Err(Error::UnsupportedVersion(h.version)),
        }
    }
}

enum MlSk {
    L65(Box<MlSigningKey<MlDsa65>>),
    L87(Box<MlSigningKey<MlDsa87>>),
}

enum TradSk {
    Ed25519(Box<ed25519_dalek::SigningKey>),
    P384(Box<p384::ecdsa::SigningKey>),
}

/// A composite secret key. Every component key zeroizes itself on drop, and so does the
/// serialized form kept here.
pub struct SecretKey {
    ml: MlSk,
    #[cfg(feature = "paranoid")]
    slh: Option<Box<slh_dsa::SigningKey<Shake256s>>>,
    trad: TradSk,
    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, "sign::SecretKey({}, <redacted>)", self.public.suite)
    }
}

impl SecretKey {
    /// Generates a fresh key pair of `suite`.
    ///
    /// # 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> {
        let mut raw = Zeroizing::new(Vec::with_capacity(secret_key_len(suite)));
        raw.extend_from_slice(&*Zeroizing::new(crate::random::<MLDSA_SEED, R>(rng)));
        #[cfg(feature = "paranoid")]
        if suite == Suite::Paranoid {
            let slh = slh_dsa::SigningKey::<Shake256s>::new(rng);
            raw.extend_from_slice(&Zeroizing::new(slh.to_bytes())[..]);
        }
        if suite == Suite::XWing {
            raw.extend_from_slice(&*Zeroizing::new(crate::random::<ED_SK, R>(rng)));
        } else {
            raw.extend_from_slice(
                &Zeroizing::new(<p384::SecretKey as p384::elliptic_curve::Generate>::generate_from_rng(rng).to_bytes())
                    [..],
            );
        }
        Self::from_raw(suite, &raw)
    }

    /// Parses a raw secret key of `suite` (no header).
    ///
    /// # Errors
    /// [`Error::InvalidLength`] or [`Error::InvalidKey`].
    pub fn from_raw(suite: Suite, raw: &[u8]) -> Result<Self> {
        let [ml_raw, slh_raw, trad_raw] = fields(raw, sk_lens(suite), "signing secret key")?;
        let xi = Zeroizing::new(ml_dsa::B32::try_from(ml_raw).map_err(|_| Error::InvalidLength("signing secret key"))?);
        let (ml, ml_pk) = if suite == Suite::XWing {
            let sk = Box::new(MlSigningKey::<MlDsa65>::from_seed(&xi));
            let pk = mldsa_public_key(&sk);
            (MlSk::L65(sk), pk)
        } else {
            let sk = Box::new(MlSigningKey::<MlDsa87>::from_seed(&xi));
            let pk = mldsa_public_key(&sk);
            (MlSk::L87(sk), pk)
        };
        #[cfg(feature = "paranoid")]
        let (slh, slh_pk) = match suite {
            Suite::Paranoid => {
                let sk = Box::new(slh_dsa::SigningKey::<Shake256s>::try_from(slh_raw).map_err(|_| Error::InvalidKey)?);
                let pk = AsRef::<slh_dsa::VerifyingKey<Shake256s>>::as_ref(&*sk)
                    .to_bytes()
                    .to_vec();
                (Some(sk), pk)
            }
            Suite::XWing | Suite::Max => (None, Vec::new()),
        };
        #[cfg(not(feature = "paranoid"))]
        let slh_pk = {
            let _ = slh_raw;
            Vec::new()
        };
        let (trad, trad_pk) = if suite == Suite::XWing {
            let seed: Zeroizing<[u8; ED_SK]> = Zeroizing::new(
                trad_raw
                    .try_into()
                    .map_err(|_| Error::InvalidLength("signing secret key"))?,
            );
            let sk = Box::new(ed25519_dalek::SigningKey::from_bytes(&seed));
            let pk = sk.verifying_key().to_bytes().to_vec();
            (TradSk::Ed25519(sk), pk)
        } else {
            let sk = Box::new(p384::ecdsa::SigningKey::from_slice(trad_raw).map_err(|_| Error::InvalidKey)?);
            let pk = p384::elliptic_curve::sec1::ToSec1Point::to_sec1_point(sk.verifying_key().as_affine(), false)
                .as_bytes()
                .to_vec();
            (TradSk::P384(sk), pk)
        };
        let public = PublicKey::from_raw(suite, &[ml_pk, slh_pk, trad_pk].concat())?;
        Ok(Self {
            ml,
            #[cfg(feature = "paranoid")]
            slh,
            trad,
            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::SignSecretKey, 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::SignSecretKey)? {
            (h, body) if h.version == VERSION_2 => Self::from_raw(policy.suite_from_id(h.suite)?, body),
            (h, _) => Err(Error::UnsupportedVersion(h.version)),
        }
    }

    /// Signs `message` with every component of the suite.
    ///
    /// # Errors
    /// [`Error::InvalidParams`] if a component fails (not reachable: the contexts are fixed and
    /// short, and the RNG is infallible).
    pub fn sign<R: Rng + ?Sized>(&self, message: &[u8], rng: &mut R) -> Result<Signature> {
        let suite = self.suite();
        let lbl = label(suite);
        let m = message_representative(suite, &self.public.fingerprint, message);
        let mut raw = Vec::with_capacity(signature_len(suite));
        raw.extend_from_slice(&match &self.ml {
            MlSk::L65(sk) => mldsa_sign(sk, &m, lbl, rng)?,
            MlSk::L87(sk) => mldsa_sign(sk, &m, lbl, rng)?,
        });
        #[cfg(feature = "paranoid")]
        if let Some(sk) = &self.slh {
            let opt_rand: [u8; 32] = crate::random(rng);
            let sig = sk
                .try_sign_with_context(&m, lbl, Some(&opt_rand))
                .map_err(|_| Error::InvalidParams("SLH-DSA signing failed"))?;
            raw.extend_from_slice(&sig.to_bytes());
        }
        match &self.trad {
            TradSk::Ed25519(sk) => raw.extend_from_slice(&ed25519_dalek::Signer::sign(&**sk, &m).to_bytes()),
            TradSk::P384(sk) => {
                // Low-`s` form: the only form verification accepts.
                let sig: p384::ecdsa::Signature = sk.sign(&m);
                raw.extend_from_slice(&sig.normalize_s().to_bytes());
            }
        }
        Signature::from_raw(suite, &raw)
    }
}

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

    #[test]
    fn round_trip_every_suite() {
        let mut rng = rng();
        for suite in Suite::ALL {
            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 sig = sk.sign(b"hello", &mut rng).unwrap();
            assert_eq!(sig.as_raw().len(), signature_len(suite));
            sk.public_key().verify(b"hello", &sig).unwrap();
            assert_eq!(sk.public_key().verify(b"hellO", &sig), Err(Error::BadSignature));
            let all = SuitePolicy::ALL;
            let pk = PublicKey::from_bytes_with_policy(&sk.public_key().to_bytes(), all).unwrap();
            pk.verify(
                b"hello",
                &Signature::from_bytes_with_policy(&sig.to_bytes(), all).unwrap(),
            )
            .unwrap();
            let sk2 = SecretKey::from_bytes_with_policy(&sk.to_bytes(), all).unwrap();
            assert_eq!(sk2.public_key(), sk.public_key());
            if suite != Suite::Max {
                let refused = Error::SuiteNotAllowed(suite.name());
                assert_eq!(PublicKey::from_bytes(&sk.public_key().to_bytes()), Err(refused));
                assert_eq!(Signature::from_bytes(&sig.to_bytes()), Err(refused));
                assert!(matches!(
                    SecretKey::from_bytes(&sk.to_bytes()),
                    Err(Error::SuiteNotAllowed(_))
                ));
            }
        }
    }

    #[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));
    }

    #[test]
    fn secret_types_zeroize_on_drop() {
        fn assert_zod<T: ZeroizeOnDrop>() {}
        assert_zod::<SecretKey>();
        assert_zod::<MlSigningKey<MlDsa87>>();
        #[cfg(feature = "paranoid")]
        assert_zod::<slh_dsa::SigningKey<Shake256s>>();
        assert_zod::<p384::ecdsa::SigningKey>();
        assert_zod::<ed25519_dalek::SigningKey>();
    }
}