pqbox 1.2.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
//! Cipher suites. One byte in every object header names the suite, so a key, a ciphertext or a
//! signature can never be used with another suite's algorithms.
//!
//! | Id | Name | KEM | Signature |
//! |---|---|---|---|
//! | `0x01` | `xwing` (compat only) | X-Wing (ML-KEM-768 + X25519, IETF draft) | ML-DSA-65 + Ed25519 |
//! | `0x02` | `pqbox-max` (default) | ML-KEM-1024 + ECDH P-384 | ML-DSA-87 + ECDSA P-384 |
//! | `0x03` | `pqbox-paranoid` (not recommended for new keys) | ML-KEM-1024 + Classic McEliece 8192128 + ECDH P-384 | ML-DSA-87 + SLH-DSA-SHAKE-256s + ECDSA P-384 |
//!
//! A hybrid stays secure as long as one of its components holds: KEM shared secrets are combined
//! so that breaking one component is not enough, and every signature in a suite must verify.
//! The `xwing` suite exists only for interoperability with X-Wing (hush, age-style tooling); its
//! classical half is a 256-bit curve, so its security rests on ML-KEM-768 and ML-DSA-65 alone.
//!
//! `pqbox-paranoid` is compiled only with the `paranoid` cargo feature (off by default). Its
//! SLH-DSA implementation (`slh-dsa` 0.2.0-rc.5) is a release candidate: treat the suite as
//! experimental.
//!
//! `pqbox-paranoid` is also **not recommended for new keys**. BSI's "Notes on recent developments
//! concerning Classic McEliece" (1 October 2026) say Classic McEliece should no longer be used in
//! new developments, after structural attacks such as the heuristic key recoveries of
//! ePrint 2026/1630 and 2026/1984 (not practical against the recommended parameters). Existing
//! paranoid objects stay readable and usable, with an unchanged format, and the paranoid KEM still
//! holds as long as ML-KEM-1024 or P-384 holds. Replacing Classic McEliece (with HQC or FrodoKEM)
//! would change the bytes, so it would need a new suite id.
//!
//! # Suite policy
//!
//! Every function that parses or opens an object it did not create (`from_bytes`,
//! [`crate::seal::open`]) checks the suite in the header against a [`SuitePolicy`]. The default
//! policy accepts only `pqbox-max`, so an attacker cannot steer an application into the compat
//! `xwing` suite or into the large paranoid parsers. Each such function has a
//! `*_with_policy` twin for applications that use the other suites on purpose:
//!
//! ```
//! # #[cfg(all(feature = "suite-max", feature = "suite-xwing"))] {
//! use pqbox::{Suite, SuitePolicy};
//! let policy = SuitePolicy::default().allow(Suite::XWing);
//! assert!(policy.allows(Suite::Max) && policy.allows(Suite::XWing));
//! # }
//! ```

use crate::{Error, Result};

/// A cipher suite. Only the suites compiled into this build have a variant (see the crate's
/// cargo features); [`Suite::from_id`] and [`Suite::from_name`] refuse the others with
/// [`Error::SuiteNotEnabled`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Suite {
    /// `0x01`, compat only: X-Wing KEM and ML-DSA-65 + Ed25519 (NIST category 3), for
    /// interoperability with the X-Wing IETF draft and with hush. Never the default; its security
    /// rests on ML-KEM-768 and ML-DSA-65. Requires the `suite-xwing` cargo feature (on by
    /// default).
    #[cfg(feature = "suite-xwing")]
    XWing = 0x01,
    /// `0x02` (default): ML-KEM-1024 + ECDH P-384 and ML-DSA-87 + ECDSA P-384 (NIST category 5).
    /// Requires the `suite-max` cargo feature (on by default).
    #[cfg(feature = "suite-max")]
    Max = 0x02,
    /// `0x03`: adds Classic McEliece 8192128 to the KEM and SLH-DSA-SHAKE-256s to the signatures,
    /// so that security was meant to survive a break of lattice cryptography as well as of
    /// elliptic curves. Keys and signatures are large (a 1.3 MB public key, 34 KB signatures).
    /// Requires the `paranoid` cargo feature; experimental while `slh-dsa` is a release candidate.
    ///
    /// Not recommended for new keys: BSI advises against Classic McEliece for new developments
    /// (1 October 2026). Existing objects stay readable and usable, and the KEM still holds while
    /// ML-KEM-1024 or P-384 holds (see the `suite` module documentation).
    #[cfg(feature = "paranoid")]
    Paranoid = 0x03,
}

/// `pqbox-max`, the default suite (only in builds with the `suite-max` feature).
#[cfg(feature = "suite-max")]
impl Default for Suite {
    fn default() -> Self {
        Self::Max
    }
}

/// The canonical name of the `xwing` suite (known even when it is not compiled in).
const XWING_NAME: &str = "xwing";
/// The canonical name of the `pqbox-max` suite (known even when it is not compiled in).
const MAX_NAME: &str = "pqbox-max";
/// The canonical name of the paranoid suite (known even when it is not compiled in).
const PARANOID_NAME: &str = "pqbox-paranoid";

/// The number of suites compiled into this build.
const COUNT: usize =
    cfg!(feature = "suite-xwing") as usize + cfg!(feature = "suite-max") as usize + cfg!(feature = "paranoid") as usize;

impl Suite {
    /// Every suite compiled into this build, in id order.
    pub const ALL: [Suite; COUNT] = [
        #[cfg(feature = "suite-xwing")]
        Suite::XWing,
        #[cfg(feature = "suite-max")]
        Suite::Max,
        #[cfg(feature = "paranoid")]
        Suite::Paranoid,
    ];

    /// Parses a suite id.
    ///
    /// # Errors
    /// [`Error::UnknownSuite`], or [`Error::SuiteNotEnabled`] for the id of a suite this build
    /// does not compile (`0x01` without `suite-xwing`, `0x02` without `suite-max`, `0x03` without
    /// `paranoid`).
    pub fn from_id(id: u8) -> Result<Self> {
        match id {
            #[cfg(feature = "suite-xwing")]
            0x01 => Ok(Self::XWing),
            #[cfg(not(feature = "suite-xwing"))]
            0x01 => Err(Error::SuiteNotEnabled(XWING_NAME)),
            #[cfg(feature = "suite-max")]
            0x02 => Ok(Self::Max),
            #[cfg(not(feature = "suite-max"))]
            0x02 => Err(Error::SuiteNotEnabled(MAX_NAME)),
            #[cfg(feature = "paranoid")]
            0x03 => Ok(Self::Paranoid),
            #[cfg(not(feature = "paranoid"))]
            0x03 => Err(Error::SuiteNotEnabled(PARANOID_NAME)),
            other => Err(Error::UnknownSuite(other)),
        }
    }

    /// The suite id.
    #[must_use]
    pub fn id(self) -> u8 {
        self as u8
    }

    /// The canonical name.
    #[must_use]
    pub fn name(self) -> &'static str {
        match self {
            #[cfg(feature = "suite-xwing")]
            Self::XWing => XWING_NAME,
            #[cfg(feature = "suite-max")]
            Self::Max => MAX_NAME,
            #[cfg(feature = "paranoid")]
            Self::Paranoid => PARANOID_NAME,
        }
    }

    /// The KEM components, post-quantum first.
    #[must_use]
    pub fn kem_components(self) -> &'static [&'static str] {
        match self {
            #[cfg(feature = "suite-xwing")]
            Self::XWing => &["ML-KEM-768", "X25519"],
            #[cfg(feature = "suite-max")]
            Self::Max => &["ML-KEM-1024", "ECDH-P384"],
            #[cfg(feature = "paranoid")]
            Self::Paranoid => &["ML-KEM-1024", "Classic-McEliece-8192128", "ECDH-P384"],
        }
    }

    /// The signature components, post-quantum first.
    #[must_use]
    pub fn signature_components(self) -> &'static [&'static str] {
        match self {
            #[cfg(feature = "suite-xwing")]
            Self::XWing => &["ML-DSA-65", "Ed25519"],
            #[cfg(feature = "suite-max")]
            Self::Max => &["ML-DSA-87", "ECDSA-P384-SHA384"],
            #[cfg(feature = "paranoid")]
            Self::Paranoid => &["ML-DSA-87", "SLH-DSA-SHAKE-256s", "ECDSA-P384-SHA384"],
        }
    }

    /// Whether this suite is kept only for interoperability (never a default).
    #[must_use]
    pub fn is_compat_only(self) -> bool {
        self.id() == 0x01
    }

    /// Parses a suite name: `xwing`, `pqbox-max` (or `max`), `pqbox-paranoid` (or `paranoid`).
    ///
    /// # Errors
    /// [`Error::InvalidParams`] for an unknown name, [`Error::SuiteNotEnabled`] for the name of a
    /// suite this build does not compile.
    pub fn from_name(name: &str) -> Result<Self> {
        match name.to_ascii_lowercase().replace('_', "-").as_str() {
            "xwing" | "x-wing" => Self::from_id(0x01),
            "pqbox-max" | "max" => Self::from_id(0x02),
            "pqbox-paranoid" | "paranoid" => Self::from_id(0x03),
            _ => Err(Error::InvalidParams("unknown suite")),
        }
    }
}

impl core::fmt::Display for Suite {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        f.write_str(self.name())
    }
}

impl core::str::FromStr for Suite {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        Self::from_name(s)
    }
}

/// The suites that parsing and opening accept.
///
/// The default, [`SuitePolicy::DEFAULT`], accepts only `pqbox-max`. `xwing` (compat) and
/// `pqbox-paranoid` must be allowed explicitly with [`SuitePolicy::allow`]. Functions that
/// create objects from an explicit suite (`generate`, `from_raw`) are not subject to a policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SuitePolicy {
    /// Bit `id` set when the suite with that id is allowed.
    mask: u8,
}

impl SuitePolicy {
    /// Only `pqbox-max`. In a build without the `suite-max` feature, no suite at all: the other
    /// suites must always be allowed explicitly.
    #[cfg(feature = "suite-max")]
    pub const DEFAULT: Self = Self::only(Suite::Max);
    /// Only `pqbox-max`. In a build without the `suite-max` feature, no suite at all: the other
    /// suites must always be allowed explicitly.
    #[cfg(not(feature = "suite-max"))]
    pub const DEFAULT: Self = Self::NONE;
    /// No suite at all; build up from it with [`SuitePolicy::allow`].
    pub const NONE: Self = Self { mask: 0 };
    /// Every suite compiled into this build. Meant for tools and tests that handle every suite
    /// on purpose.
    pub const ALL: Self = {
        let p = Self::NONE;
        #[cfg(feature = "suite-xwing")]
        let p = p.allow(Suite::XWing);
        #[cfg(feature = "suite-max")]
        let p = p.allow(Suite::Max);
        #[cfg(feature = "paranoid")]
        let p = p.allow(Suite::Paranoid);
        p
    };

    /// Exactly one suite.
    #[must_use]
    pub const fn only(suite: Suite) -> Self {
        Self::NONE.allow(suite)
    }

    /// This policy plus `suite`.
    #[must_use]
    pub const fn allow(self, suite: Suite) -> Self {
        Self {
            mask: self.mask | (1 << suite as u8),
        }
    }

    /// Whether `suite` is allowed.
    #[must_use]
    pub const fn allows(self, suite: Suite) -> bool {
        self.mask & (1 << suite as u8) != 0
    }

    /// The allowed suites, in id order.
    pub fn suites(self) -> impl Iterator<Item = Suite> {
        Suite::ALL.into_iter().filter(move |s| self.allows(*s))
    }

    /// Checks `suite` against the policy.
    ///
    /// # Errors
    /// [`Error::SuiteNotAllowed`].
    pub fn check(self, suite: Suite) -> Result<Suite> {
        if self.allows(suite) {
            Ok(suite)
        } else {
            Err(Error::SuiteNotAllowed(suite.name()))
        }
    }

    /// This policy plus the suites named in `names` (see [`Suite::from_name`]), for bindings
    /// and command-line options that take suite names.
    ///
    /// # Errors
    /// [`Error::UnknownSuite`] or [`Error::SuiteNotEnabled`] for a name this build cannot use.
    pub fn allow_names<'a>(self, names: impl IntoIterator<Item = &'a str>) -> Result<Self> {
        names
            .into_iter()
            .try_fold(self, |p, name| Ok(p.allow(Suite::from_name(name)?)))
    }

    /// Parses a suite id from a header and checks it against the policy.
    ///
    /// # Errors
    /// [`Error::UnknownSuite`], [`Error::SuiteNotEnabled`] or [`Error::SuiteNotAllowed`].
    pub fn suite_from_id(self, id: u8) -> Result<Suite> {
        self.check(Suite::from_id(id)?)
    }
}

impl Default for SuitePolicy {
    fn default() -> Self {
        Self::DEFAULT
    }
}

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

    #[test]
    fn ids_and_names_round_trip() {
        for s in Suite::ALL {
            assert_eq!(Suite::from_id(s.id()).unwrap(), s);
            assert_eq!(Suite::from_name(s.name()).unwrap(), s);
        }
        assert_eq!(Suite::from_id(0), Err(Error::UnknownSuite(0)));
        assert_eq!(Suite::from_id(4), Err(Error::UnknownSuite(4)));
        assert!(Suite::from_name("rsa").is_err());
        #[cfg(feature = "suite-max")]
        assert_eq!(Suite::default(), Suite::Max);
        // A suite that is compiled out is refused by id and by name, never read as another one.
        for (id, name, enabled) in [
            (1, "xwing", cfg!(feature = "suite-xwing")),
            (2, "pqbox-max", cfg!(feature = "suite-max")),
            (3, "pqbox-paranoid", cfg!(feature = "paranoid")),
        ] {
            if enabled {
                assert_eq!(Suite::from_id(id).unwrap().name(), name);
                assert_eq!(Suite::from_name(name).unwrap().id(), id);
            } else {
                assert_eq!(Suite::from_id(id), Err(Error::SuiteNotEnabled(name)));
                assert_eq!(Suite::from_name(name), Err(Error::SuiteNotEnabled(name)));
                assert_eq!(SuitePolicy::ALL.suite_from_id(id), Err(Error::SuiteNotEnabled(name)));
            }
        }
        assert_eq!(
            Suite::ALL.len(),
            [
                cfg!(feature = "suite-xwing"),
                cfg!(feature = "suite-max"),
                cfg!(feature = "paranoid")
            ]
            .into_iter()
            .filter(|e| *e)
            .count()
        );
    }

    #[cfg(feature = "suite-max")]
    #[test]
    fn default_policy_accepts_only_max() {
        let p = SuitePolicy::default();
        assert_eq!(p, SuitePolicy::DEFAULT);
        assert!(p.allows(Suite::Max));
        assert_eq!(p.suite_from_id(2), Ok(Suite::Max));
        assert_eq!(p.suite_from_id(9), Err(Error::UnknownSuite(9)));
        assert_eq!(p.suites().collect::<Vec<_>>(), [Suite::Max]);
        #[cfg(feature = "suite-xwing")]
        {
            assert!(!p.allows(Suite::XWing));
            assert_eq!(p.check(Suite::XWing), Err(Error::SuiteNotAllowed("xwing")));
            assert_eq!(p.suite_from_id(1), Err(Error::SuiteNotAllowed("xwing")));
            let x = p.allow(Suite::XWing);
            assert!(x.allows(Suite::XWing) && x.allows(Suite::Max));
            assert_eq!(
                SuitePolicy::only(Suite::XWing).check(Suite::Max),
                Err(Error::SuiteNotAllowed("pqbox-max"))
            );
        }
        #[cfg(feature = "paranoid")]
        {
            assert!(!p.allows(Suite::Paranoid));
            assert_eq!(p.suite_from_id(3), Err(Error::SuiteNotAllowed("pqbox-paranoid")));
        }
        assert!(!SuitePolicy::NONE.allows(Suite::Max));
    }

    /// Without `suite-max`, the default policy accepts nothing: `xwing` stays opt-in.
    #[cfg(not(feature = "suite-max"))]
    #[test]
    fn default_policy_without_max_accepts_nothing() {
        assert_eq!(SuitePolicy::DEFAULT, SuitePolicy::NONE);
        assert_eq!(SuitePolicy::default().suites().count(), 0);
        assert_eq!(
            SuitePolicy::DEFAULT.suite_from_id(1),
            Err(Error::SuiteNotAllowed("xwing"))
        );
        assert_eq!(
            SuitePolicy::DEFAULT.suite_from_id(2),
            Err(Error::SuiteNotEnabled("pqbox-max"))
        );
    }

    #[test]
    fn policy_all_is_every_compiled_suite() {
        assert_eq!(SuitePolicy::ALL.suites().collect::<Vec<_>>(), Suite::ALL.to_vec());
        for s in Suite::ALL {
            assert!(SuitePolicy::ALL.allows(s));
            assert!(!SuitePolicy::NONE.allows(s));
        }
    }

    /// No default or recommended suite relies on a 256-bit curve, and every one carries ML-KEM
    /// and ML-DSA at category 5.
    #[test]
    fn non_compat_suites_are_post_quantum_with_p384() {
        #[cfg(feature = "suite-max")]
        assert!(!Suite::default().is_compat_only());
        for s in Suite::ALL.into_iter().filter(|s| !s.is_compat_only()) {
            assert!(s.kem_components().contains(&"ML-KEM-1024"), "{s}");
            assert!(s.signature_components().contains(&"ML-DSA-87"), "{s}");
            for c in s.kem_components().iter().chain(s.signature_components()) {
                assert!(!["X25519", "Ed25519", "P-256", "secp256k1"].contains(c), "{s}: {c}");
            }
            assert!(s.kem_components().contains(&"ECDH-P384"), "{s}");
            assert!(s.signature_components().contains(&"ECDSA-P384-SHA384"), "{s}");
        }
        // Every suite, compat included, has a post-quantum KEM and signature.
        for s in Suite::ALL {
            assert!(s.kem_components()[0].starts_with("ML-KEM"), "{s}");
            assert!(s.signature_components()[0].starts_with("ML-DSA"), "{s}");
        }
    }
}