Skip to main content

pq_mceliece/
lib.rs

1/*
2    Copyright Michael Lodder. All Rights Reserved.
3    SPDX-License-Identifier: Apache-2.0 OR MIT
4*/
5//! A pure Rust implementation of the Classic McEliece key encapsulation mechanism.
6//!
7//! Every enabled parameter set is available at once. Unlike implementations that bake a single
8//! parameter set into the crate through cargo features, this crate makes choosing between
9//! `mceliece348864` and `mceliece8192128pcf` a runtime decision.
10//!
11//! ## Usage
12//!
13//! The straightforward path is [`Algorithm`], which carries the parameter set as a value:
14//!
15//! ```
16//! # #[cfg(all(
17//! #     feature = "mceliece348864f",
18//! #     feature = "keygen",
19//! #     feature = "encapsulate",
20//! #     feature = "decapsulate"
21//! # ))] {
22//! use pq_mceliece::Algorithm;
23//! use rand::SeedableRng;
24//! use rand::rngs::{StdRng, SysRng};
25//!
26//! // A cryptographically secure generator, seeded once from the operating system.
27//! let mut rng = StdRng::try_from_rng(&mut SysRng).unwrap();
28//!
29//! let alg = Algorithm::McEliece348864f;
30//! let (ek, dk) = alg.generate_keypair(&mut rng);
31//! let (ct, sent) = alg.encapsulate(&ek, &mut rng).unwrap();
32//! let received = alg.decapsulate(&dk, &ct).unwrap();
33//!
34//! assert_eq!(sent, received);
35//! # }
36//! ```
37//!
38//! Key generation is deterministic in a 32-byte seed, so a key pair can be reproduced from
39//! backed-up seed material:
40//!
41//! ```
42//! # #[cfg(feature = "keygen")] {
43//! use pq_mceliece::Algorithm;
44//!
45//! // Any enabled parameter set works; `default` picks the first one.
46//! let alg = Algorithm::default();
47//! let seed = [0x42u8; 32];
48//! let first = alg.generate_keypair_from_seed(seed).unwrap();
49//! let second = alg.generate_keypair_from_seed(seed).unwrap();
50//! assert_eq!(first, second);
51//! # }
52//! ```
53//!
54//! When the parameter set is known at compile time, the [`hazmat`] layer offers the same
55//! operations with the parameter set in the type, so a key from one parameter set cannot be
56//! passed to another:
57//!
58//! ```
59//! # #[cfg(all(
60//! #     feature = "mceliece348864",
61//! #     feature = "hazmat",
62//! #     feature = "keygen",
63//! #     feature = "encapsulate",
64//! #     feature = "decapsulate"
65//! # ))] {
66//! use pq_mceliece::hazmat::{Kem, McEliece348864};
67//! use rand::SeedableRng;
68//! use rand::rngs::{StdRng, SysRng};
69//!
70//! let mut rng = StdRng::try_from_rng(&mut SysRng).unwrap();
71//!
72//! let (ek, dk) = McEliece348864::generate_keypair(&mut rng);
73//! let (ct, sent) = McEliece348864::encapsulate(&ek, &mut rng).unwrap();
74//! let received = McEliece348864::decapsulate(&dk, &ct).unwrap();
75//!
76//! assert_eq!(sent, received);
77//! # }
78//! ```
79//!
80//! Implementations of the [`kem`](https://docs.rs/kem) crate traits live in the [`kem`] module.
81//!
82//! ## Standards
83//!
84//! | parameter sets | NIST round 4 | ISO |
85//! | -------------- | ------------ | --- |
86//! | `mceliece348864`, `mceliece348864f` | yes | no |
87//! | `mceliece460896`, `mceliece6688128`, `mceliece6960119`, `mceliece8192128`, and their `f` variants | yes | yes |
88//! | the `pc` and `pcf` variants of those four sizes | no | yes |
89//!
90//! The `pc` parameter sets add *plaintext confirmation*: the ciphertext carries an extra
91//! 32-byte hash of the error vector, which decapsulation checks before deriving the session
92//! key. They are part of the ISO standard published in June 2026 and are not in the NIST
93//! submission.
94//!
95//! Implementation choices follow the *narrowly decoded* reading of the specification:
96//! encapsulation keys and ciphertexts with nonzero padding bits are rejected rather than
97//! ignored. This only ever applies to `mceliece6960119`, the one standardized parameter set
98//! whose `mt` and `k` are not multiples of eight.
99//!
100//! ## Choosing a parameter set
101//!
102//! **Use [`Algorithm::RECOMMENDED`] (`mceliece6960119f`) unless something else decides for
103//! you.** The Classic McEliece team [recommends the `mceliece6*` sizes for long-term
104//! security](https://classic.mceliece.org/iso.html), and the `f` variants generate keys
105//! faster while drawing them from the same distribution.
106//!
107//! **`mceliece348864` is for research, testing, and interop only — not production.** It
108//! exists because NIST asked for a Category 1 (lowest security floor) parameter set, and it
109//! has the thinnest security margin of the family: the team's
110//! [CryptAttackTester](https://blog.cr.yp.to/20250423-mceliece.html) analysis puts the best
111//! known attacks — message recovery by information-set decoding — at about 2^150.59 bit
112//! operations, versus 2^190.50 for `mceliece460896` and above 2^257 for the `mceliece6*`
113//! sizes. The ISO standard requires at least 128 bits of security in its quantum model,
114//! which assumes a square-root Grover speedup; `mceliece348864` does not clear that bar and
115//! is [excluded from the ISO standard](https://classic.mceliece.org/iso.html), while
116//! `mceliece460896` was admitted because Grover's speedup is limited by attack latency.
117//! (Key-recovery attacks are not the concern: the team's analysis finds them far slower
118//! than message recovery for every standardized set.)
119//!
120//! In between, `mceliece460896` (NIST Category 3, ISO-standardized) is the smallest
121//! production-appropriate set, and `mceliece8192128` trades a larger key for power-of-two
122//! dimensions and no padding. The `pc` variants add plaintext confirmation where a protocol
123//! requires it.
124//!
125//! ## Conformance
126//!
127//! Every NIST parameter set is checked bit for bit against the published `kat_kem.rsp` known
128//! answer tests. See
129//! [`CONFORMANCE.md`](https://github.com/mikelodder7/pq-mceliece/blob/main/CONFORMANCE.md)
130//! for what is verified and how.
131//!
132//! ## Features
133//!
134//! Parameter sets and operations are selected independently.
135//!
136//! Each parameter set has its own feature, and the `nist`, `iso` and `pc` groups enable the
137//! corresponding sets.
138//!
139//! The three operations are `keygen`, `encapsulate` and `decapsulate`. At least one must be
140//! enabled, and a build only carries the code and dependencies the enabled ones reach.
141//! Encapsulation is by far the lightest: `Encode` is pure bit manipulation over the public key,
142//! so an encapsulate-only build contains no field arithmetic, no polynomial arithmetic, no
143//! matrix reduction, no sorting networks and no Beneš network.
144//!
145//! | feature | effect |
146//! | ------- | ------ |
147//! | `keygen` | `KeyGen` and `SeededKeyGen`, and recovering a public key from a private one |
148//! | `encapsulate` | `Encap` |
149//! | `decapsulate` | `Decap` |
150//! | `kem` | the [`kem`](https://docs.rs/kem) crate traits; implies all three operations |
151//! | `serde` | serialization for every value type |
152//! | `hazmat` | makes the low-level layer public |
153#![warn(
154    missing_docs,
155    missing_debug_implementations,
156    missing_copy_implementations,
157    trivial_casts,
158    trivial_numeric_casts,
159    unused,
160    clippy::mod_module_files
161)]
162#![deny(clippy::unwrap_used)]
163
164#[cfg(not(any(
165    feature = "mceliece348864",
166    feature = "mceliece348864f",
167    feature = "mceliece460896",
168    feature = "mceliece460896f",
169    feature = "mceliece460896pc",
170    feature = "mceliece460896pcf",
171    feature = "mceliece6688128",
172    feature = "mceliece6688128f",
173    feature = "mceliece6688128pc",
174    feature = "mceliece6688128pcf",
175    feature = "mceliece6960119",
176    feature = "mceliece6960119f",
177    feature = "mceliece6960119pc",
178    feature = "mceliece6960119pcf",
179    feature = "mceliece8192128",
180    feature = "mceliece8192128f",
181    feature = "mceliece8192128pc",
182    feature = "mceliece8192128pcf",
183)))]
184compile_error!("no Classic McEliece parameter set feature is enabled");
185
186#[cfg(not(any(feature = "keygen", feature = "encapsulate", feature = "decapsulate")))]
187compile_error!(
188    "no Classic McEliece operation feature is enabled; \
189     select at least one of `keygen`, `encapsulate` or `decapsulate`"
190);
191
192/// Compiles the README's examples as doctests so they cannot drift from the API.
193///
194/// Only exists under `cargo test --doc`, so it adds nothing to the rendered documentation or
195/// to a normal build. Gated on everything the examples name, so that a build without those
196/// features skips them rather than failing on code it was never going to compile. That keeps
197/// the feature gating in here instead of scattered through the README, where hidden doctest
198/// lines would still be visible to anyone reading it on the repository page.
199#[cfg(all(
200    doctest,
201    feature = "hazmat",
202    feature = "kem",
203    feature = "mceliece348864f",
204    feature = "mceliece460896f",
205    feature = "mceliece6960119f",
206    feature = "mceliece8192128f"
207))]
208#[doc = include_str!("../README.md")]
209pub struct ReadmeExamples;
210
211mod error;
212pub use error::*;
213
214#[cfg(feature = "kem")]
215pub mod kem;
216
217#[cfg(feature = "hazmat")]
218pub mod hazmat;
219#[cfg(not(feature = "hazmat"))]
220mod hazmat;
221
222use ctutils::{Choice, CtEq};
223#[cfg(feature = "keygen")]
224use hazmat::Kem;
225use hazmat::Params;
226#[cfg(any(feature = "keygen", feature = "encapsulate"))]
227use rand_core::CryptoRng;
228use zeroize::{Zeroize, ZeroizeOnDrop};
229
230/// Run `$body` with `$p` bound to the parameter set of `$alg`.
231///
232/// Every dynamic operation funnels through this, so adding a parameter set means adding one
233/// arm here and one entry to [`Algorithm`].
234macro_rules! with_params {
235    ($alg:expr, $p:ident, $body:block) => {
236        match $alg {
237            #[cfg(feature = "mceliece348864")]
238            Algorithm::McEliece348864 => {
239                type $p = hazmat::McEliece348864;
240                $body
241            }
242            #[cfg(feature = "mceliece348864f")]
243            Algorithm::McEliece348864f => {
244                type $p = hazmat::McEliece348864f;
245                $body
246            }
247            #[cfg(feature = "mceliece460896")]
248            Algorithm::McEliece460896 => {
249                type $p = hazmat::McEliece460896;
250                $body
251            }
252            #[cfg(feature = "mceliece460896f")]
253            Algorithm::McEliece460896f => {
254                type $p = hazmat::McEliece460896f;
255                $body
256            }
257            #[cfg(feature = "mceliece460896pc")]
258            Algorithm::McEliece460896pc => {
259                type $p = hazmat::McEliece460896pc;
260                $body
261            }
262            #[cfg(feature = "mceliece460896pcf")]
263            Algorithm::McEliece460896pcf => {
264                type $p = hazmat::McEliece460896pcf;
265                $body
266            }
267            #[cfg(feature = "mceliece6688128")]
268            Algorithm::McEliece6688128 => {
269                type $p = hazmat::McEliece6688128;
270                $body
271            }
272            #[cfg(feature = "mceliece6688128f")]
273            Algorithm::McEliece6688128f => {
274                type $p = hazmat::McEliece6688128f;
275                $body
276            }
277            #[cfg(feature = "mceliece6688128pc")]
278            Algorithm::McEliece6688128pc => {
279                type $p = hazmat::McEliece6688128pc;
280                $body
281            }
282            #[cfg(feature = "mceliece6688128pcf")]
283            Algorithm::McEliece6688128pcf => {
284                type $p = hazmat::McEliece6688128pcf;
285                $body
286            }
287            #[cfg(feature = "mceliece6960119")]
288            Algorithm::McEliece6960119 => {
289                type $p = hazmat::McEliece6960119;
290                $body
291            }
292            #[cfg(feature = "mceliece6960119f")]
293            Algorithm::McEliece6960119f => {
294                type $p = hazmat::McEliece6960119f;
295                $body
296            }
297            #[cfg(feature = "mceliece6960119pc")]
298            Algorithm::McEliece6960119pc => {
299                type $p = hazmat::McEliece6960119pc;
300                $body
301            }
302            #[cfg(feature = "mceliece6960119pcf")]
303            Algorithm::McEliece6960119pcf => {
304                type $p = hazmat::McEliece6960119pcf;
305                $body
306            }
307            #[cfg(feature = "mceliece8192128")]
308            Algorithm::McEliece8192128 => {
309                type $p = hazmat::McEliece8192128;
310                $body
311            }
312            #[cfg(feature = "mceliece8192128f")]
313            Algorithm::McEliece8192128f => {
314                type $p = hazmat::McEliece8192128f;
315                $body
316            }
317            #[cfg(feature = "mceliece8192128pc")]
318            Algorithm::McEliece8192128pc => {
319                type $p = hazmat::McEliece8192128pc;
320                $body
321            }
322            #[cfg(feature = "mceliece8192128pcf")]
323            Algorithm::McEliece8192128pcf => {
324                type $p = hazmat::McEliece8192128pcf;
325                $body
326            }
327        }
328    };
329}
330
331/// Declare the [`Algorithm`] enum along with its name and identifier mappings.
332macro_rules! declare_algorithms {
333    ($(
334        $(#[$meta:meta])*
335        $feature:literal => $variant:ident, $id:literal;
336    )+) => {
337        /// A Classic McEliece parameter set, selected at run time.
338        #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
339        #[non_exhaustive]
340        pub enum Algorithm {
341            $(
342                $(#[$meta])*
343                #[cfg(feature = $feature)]
344                $variant,
345            )+
346        }
347
348        impl Algorithm {
349            /// Every parameter set enabled in this build, in a stable order.
350            pub const fn enabled_algorithms() -> &'static [Algorithm] {
351                &[
352                    $(
353                        #[cfg(feature = $feature)]
354                        Self::$variant,
355                    )+
356                ]
357            }
358        }
359
360        impl From<Algorithm> for u8 {
361            fn from(algorithm: Algorithm) -> u8 {
362                match algorithm {
363                    $(
364                        #[cfg(feature = $feature)]
365                        Algorithm::$variant => $id,
366                    )+
367                }
368            }
369        }
370
371        impl TryFrom<u8> for Algorithm {
372            type Error = Error;
373
374            fn try_from(value: u8) -> Result<Self, Self::Error> {
375                match value {
376                    $(
377                        #[cfg(feature = $feature)]
378                        $id => Ok(Algorithm::$variant),
379                    )+
380                    _ => Err(Error::UnsupportedAlgorithm),
381                }
382            }
383        }
384
385        impl core::str::FromStr for Algorithm {
386            type Err = Error;
387
388            fn from_str(s: &str) -> Result<Self, Self::Err> {
389                match s {
390                    $(
391                        #[cfg(feature = $feature)]
392                        $feature => Ok(Algorithm::$variant),
393                    )+
394                    _ => Err(Error::UnsupportedAlgorithm),
395                }
396            }
397        }
398    };
399}
400
401declare_algorithms! {
402    /// `mceliece348864`: NIST category 1. In the NIST submission only.
403    "mceliece348864" => McEliece348864, 1;
404    /// `mceliece348864f`: `mceliece348864` with faster semi-systematic key generation.
405    "mceliece348864f" => McEliece348864f, 2;
406    /// `mceliece460896`: NIST category 3.
407    "mceliece460896" => McEliece460896, 3;
408    /// `mceliece460896f`: `mceliece460896` with faster semi-systematic key generation.
409    "mceliece460896f" => McEliece460896f, 4;
410    /// `mceliece460896pc`: `mceliece460896` with plaintext confirmation. ISO only.
411    "mceliece460896pc" => McEliece460896pc, 5;
412    /// `mceliece460896pcf`: plaintext confirmation and semi-systematic key generation.
413    "mceliece460896pcf" => McEliece460896pcf, 6;
414    /// `mceliece6688128`: NIST category 5.
415    "mceliece6688128" => McEliece6688128, 7;
416    /// `mceliece6688128f`: `mceliece6688128` with faster semi-systematic key generation.
417    "mceliece6688128f" => McEliece6688128f, 8;
418    /// `mceliece6688128pc`: `mceliece6688128` with plaintext confirmation. ISO only.
419    "mceliece6688128pc" => McEliece6688128pc, 9;
420    /// `mceliece6688128pcf`: plaintext confirmation and semi-systematic key generation.
421    "mceliece6688128pcf" => McEliece6688128pcf, 10;
422    /// `mceliece6960119`: NIST category 5.
423    "mceliece6960119" => McEliece6960119, 11;
424    /// `mceliece6960119f`: `mceliece6960119` with faster semi-systematic key generation.
425    "mceliece6960119f" => McEliece6960119f, 12;
426    /// `mceliece6960119pc`: `mceliece6960119` with plaintext confirmation. ISO only.
427    "mceliece6960119pc" => McEliece6960119pc, 13;
428    /// `mceliece6960119pcf`: plaintext confirmation and semi-systematic key generation.
429    "mceliece6960119pcf" => McEliece6960119pcf, 14;
430    /// `mceliece8192128`: NIST category 5.
431    "mceliece8192128" => McEliece8192128, 15;
432    /// `mceliece8192128f`: `mceliece8192128` with faster semi-systematic key generation.
433    "mceliece8192128f" => McEliece8192128f, 16;
434    /// `mceliece8192128pc`: `mceliece8192128` with plaintext confirmation. ISO only.
435    "mceliece8192128pc" => McEliece8192128pc, 17;
436    /// `mceliece8192128pcf`: plaintext confirmation and semi-systematic key generation.
437    "mceliece8192128pcf" => McEliece8192128pcf, 18;
438}
439
440impl Algorithm {
441    /// The parameter set to use when nothing else decides it: [`McEliece6960119f`].
442    ///
443    /// The Classic McEliece team [recommends the `mceliece6*` sizes for long-term
444    /// security](https://classic.mceliece.org/iso.html), and `mceliece6960119` is the
445    /// original 1978-lineage size among them; the `f` variant generates keys faster and
446    /// draws them from the same distribution. See the crate documentation's *Choosing a
447    /// parameter set* section for how the alternatives compare, and why `mceliece348864`
448    /// is for research rather than production.
449    ///
450    /// [`McEliece6960119f`]: Algorithm::McEliece6960119f
451    #[cfg(feature = "mceliece6960119f")]
452    pub const RECOMMENDED: Algorithm = Algorithm::McEliece6960119f;
453}
454
455impl Default for Algorithm {
456    fn default() -> Self {
457        Self::enabled_algorithms()[0]
458    }
459}
460
461impl core::fmt::Display for Algorithm {
462    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
463        f.write_str(self.name())
464    }
465}
466
467impl CtEq for Algorithm {
468    fn ct_eq(&self, other: &Self) -> Choice {
469        u8::from(*self).ct_eq(&u8::from(*other))
470    }
471}
472
473macro_rules! widening_conversions {
474    ($($ty:ty),+) => {
475        $(
476            impl From<Algorithm> for $ty {
477                fn from(algorithm: Algorithm) -> Self {
478                    u8::from(algorithm) as $ty
479                }
480            }
481
482            impl TryFrom<$ty> for Algorithm {
483                type Error = Error;
484
485                fn try_from(value: $ty) -> Result<Self, Self::Error> {
486                    u8::try_from(value)
487                        .map_err(|_| Error::UnsupportedAlgorithm)?
488                        .try_into()
489                }
490            }
491        )+
492    };
493}
494
495widening_conversions!(u16, u32, u64, u128, usize);
496
497/// The parameters underlying an [`Algorithm`].
498#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
499#[non_exhaustive]
500pub struct AlgorithmParams {
501    /// The parameter set name.
502    pub name: &'static str,
503    /// The extension degree `m`, so that the field is `GF(2^m)`.
504    pub m: usize,
505    /// The code length `n`.
506    pub n: usize,
507    /// The number of correctable errors `t`, and the degree of the Goppa polynomial.
508    pub t: usize,
509    /// The code dimension `k = n - mt`.
510    pub k: usize,
511    /// The semi-systematic parameters `(mu, nu)`. `(0, 0)` for non-`f` parameter sets.
512    pub semi_systematic: (usize, usize),
513    /// Whether the parameter set uses plaintext confirmation.
514    pub plaintext_confirmation: bool,
515    /// The claimed NIST security category.
516    pub claimed_nist_level: usize,
517    /// Whether the parameter set is in the NIST round-4 submission.
518    pub in_nist_submission: bool,
519    /// Whether the parameter set is in the ISO standard.
520    pub in_iso_standard: bool,
521    /// The byte length of an encapsulation key.
522    pub encapsulation_key_length: usize,
523    /// The byte length of a decapsulation key.
524    pub decapsulation_key_length: usize,
525    /// The byte length of a ciphertext.
526    pub ciphertext_length: usize,
527    /// The byte length of a shared secret.
528    pub shared_secret_length: usize,
529    /// The byte length of a key-generation seed.
530    pub seed_length: usize,
531}
532
533macro_rules! serde_impl {
534    ($name:ident, $from_method:ident) => {
535        #[cfg(feature = "serde")]
536        impl serde::Serialize for $name {
537            fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
538            where
539                S: serde::Serializer,
540            {
541                if s.is_human_readable() {
542                    use serde::ser::SerializeStruct;
543
544                    let mut map = s.serialize_struct(stringify!($name), 2)?;
545                    map.serialize_field("algorithm", self.algorithm.name())?;
546                    map.serialize_field("value", &hex::encode(&self.value))?;
547                    map.end()
548                } else {
549                    let mut seq = Vec::with_capacity(self.value.len() + 1);
550                    seq.push(u8::from(self.algorithm));
551                    seq.extend_from_slice(&self.value);
552                    s.serialize_bytes(&seq)
553                }
554            }
555        }
556
557        #[cfg(feature = "serde")]
558        impl<'de> serde::Deserialize<'de> for $name {
559            fn deserialize<D>(d: D) -> Result<Self, D::Error>
560            where
561                D: serde::Deserializer<'de>,
562            {
563                if d.is_human_readable() {
564                    #[derive(serde::Deserialize)]
565                    #[serde(field_identifier, rename_all = "snake_case")]
566                    enum Field {
567                        Algorithm,
568                        Value,
569                    }
570
571                    struct StructVisitor;
572
573                    impl<'de> serde::de::Visitor<'de> for StructVisitor {
574                        type Value = $name;
575
576                        fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
577                            write!(f, "a struct with an algorithm and a hex value")
578                        }
579
580                        fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
581                        where
582                            A: serde::de::MapAccess<'de>,
583                        {
584                            let mut algorithm = Option::<Algorithm>::None;
585                            let mut value = Option::<String>::None;
586                            while let Some(key) = map.next_key()? {
587                                match key {
588                                    Field::Algorithm => {
589                                        if algorithm.is_some() {
590                                            return Err(serde::de::Error::duplicate_field(
591                                                "algorithm",
592                                            ));
593                                        }
594                                        algorithm = Some(map.next_value()?);
595                                    }
596                                    Field::Value => {
597                                        if value.is_some() {
598                                            return Err(serde::de::Error::duplicate_field("value"));
599                                        }
600                                        value = Some(map.next_value()?);
601                                    }
602                                }
603                            }
604
605                            let algorithm = algorithm
606                                .ok_or_else(|| serde::de::Error::missing_field("algorithm"))?;
607                            let value =
608                                value.ok_or_else(|| serde::de::Error::missing_field("value"))?;
609                            let value = hex::decode(&value).map_err(serde::de::Error::custom)?;
610                            algorithm
611                                .$from_method(&value)
612                                .map_err(serde::de::Error::custom)
613                        }
614                    }
615
616                    const FIELDS: &[&str] = &["algorithm", "value"];
617                    d.deserialize_struct(stringify!($name), FIELDS, StructVisitor)
618                } else {
619                    struct BytesVisitor;
620
621                    impl<'de> serde::de::Visitor<'de> for BytesVisitor {
622                        type Value = $name;
623
624                        fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
625                            write!(f, "a byte sequence")
626                        }
627
628                        fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
629                        where
630                            E: serde::de::Error,
631                        {
632                            let (tag, value) = v.split_first().ok_or_else(|| {
633                                serde::de::Error::custom(Error::UnsupportedAlgorithm)
634                            })?;
635                            let algorithm =
636                                Algorithm::try_from(*tag).map_err(serde::de::Error::custom)?;
637                            algorithm
638                                .$from_method(value)
639                                .map_err(serde::de::Error::custom)
640                        }
641                    }
642
643                    d.deserialize_bytes(BytesVisitor)
644                }
645            }
646        }
647    };
648}
649
650macro_rules! value_type {
651    (
652        $(#[$meta:meta])*
653        $name:ident, $from_method:ident, secret = $secret:literal, length = $length:ident
654    ) => {
655        $(#[$meta])*
656        #[derive(Clone)]
657        pub struct $name {
658            pub(crate) algorithm: Algorithm,
659            pub(crate) value: Vec<u8>,
660        }
661
662        impl Default for $name {
663            /// An all-zero value of the correct length for [`Algorithm::default`].
664            ///
665            /// A derived `Default` would produce an empty value that violates the length
666            /// invariant every constructor enforces, so this builds one that upholds it.
667            fn default() -> Self {
668                let algorithm = Algorithm::default();
669                let value = with_params!(&algorithm, P, { vec![0u8; P::$length] });
670                Self { algorithm, value }
671            }
672        }
673
674        impl $name {
675            /// The parameter set this value belongs to.
676            pub fn algorithm(&self) -> Algorithm {
677                self.algorithm
678            }
679
680            /// The raw bytes.
681            pub fn value(&self) -> &[u8] {
682                &self.value
683            }
684
685            /// Parse bytes as this value type for `algorithm`.
686            pub fn from_bytes<B: AsRef<[u8]>>(
687                algorithm: Algorithm,
688                value: B,
689            ) -> McElieceResult<Self> {
690                algorithm.$from_method(value.as_ref())
691            }
692        }
693
694        impl AsRef<[u8]> for $name {
695            fn as_ref(&self) -> &[u8] {
696                &self.value
697            }
698        }
699
700        impl CtEq for $name {
701            fn ct_eq(&self, other: &Self) -> Choice {
702                self.algorithm.ct_eq(&other.algorithm)
703                    & self.value.as_slice().ct_eq(other.value.as_slice())
704            }
705        }
706
707        impl PartialEq for $name {
708            fn eq(&self, other: &Self) -> bool {
709                bool::from(self.ct_eq(other))
710            }
711        }
712
713        impl Eq for $name {}
714
715        impl core::fmt::Debug for $name {
716            fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
717                let mut out = f.debug_struct(stringify!($name));
718                out.field("algorithm", &self.algorithm);
719                if $secret {
720                    out.finish_non_exhaustive()
721                } else {
722                    out.field("value", &self.value).finish()
723                }
724            }
725        }
726
727        serde_impl!($name, $from_method);
728    };
729}
730
731value_type! {
732    /// A Classic McEliece encapsulation (public) key.
733    EncapsulationKey, encapsulation_key_from_bytes, secret = false, length = PUBLIC_KEY_LENGTH
734}
735
736value_type! {
737    /// A Classic McEliece decapsulation (private) key.
738    DecapsulationKey, decapsulation_key_from_bytes, secret = true, length = SECRET_KEY_LENGTH
739}
740
741value_type! {
742    /// A Classic McEliece ciphertext.
743    Ciphertext, ciphertext_from_bytes, secret = false, length = CIPHERTEXT_LENGTH
744}
745
746value_type! {
747    /// A Classic McEliece shared secret.
748    SharedSecret, shared_secret_from_bytes, secret = true, length = SHARED_SECRET_LENGTH
749}
750
751macro_rules! zeroize_on_drop {
752    ($name:ident) => {
753        impl Zeroize for $name {
754            fn zeroize(&mut self) {
755                self.value.zeroize();
756            }
757        }
758
759        impl ZeroizeOnDrop for $name {}
760
761        impl Drop for $name {
762            fn drop(&mut self) {
763                self.zeroize();
764            }
765        }
766    };
767}
768
769zeroize_on_drop!(DecapsulationKey);
770zeroize_on_drop!(SharedSecret);
771
772#[cfg(feature = "encapsulate")]
773impl EncapsulationKey {
774    /// Whether every padding bit is zero.
775    ///
776    /// [`encapsulate`](Self::encapsulate) rejects a key that fails this check. Parameter sets
777    /// whose `k` is a multiple of eight have no padding, so this is always `true` for them.
778    pub fn padding_is_zero(&self) -> bool {
779        with_params!(&self.algorithm, P, {
780            match hazmat::EncapsulationKey::<P>::from_slice(&self.value) {
781                Ok(key) => key.padding_is_zero(),
782                Err(_) => false,
783            }
784        })
785    }
786
787    /// Encapsulate to this key, producing a ciphertext and the shared secret it transports.
788    pub fn encapsulate(&self, rng: impl CryptoRng) -> McElieceResult<(Ciphertext, SharedSecret)> {
789        self.algorithm.encapsulate(self, rng)
790    }
791}
792
793#[cfg(feature = "keygen")]
794impl From<&DecapsulationKey> for EncapsulationKey {
795    /// Recover the encapsulation key by rerunning key generation from the stored seed.
796    ///
797    /// This costs a full key generation.
798    fn from(secret: &DecapsulationKey) -> Self {
799        with_params!(&secret.algorithm, P, {
800            match hazmat::DecapsulationKey::<P>::from_slice(&secret.value) {
801                Ok(typed) => EncapsulationKey {
802                    algorithm: secret.algorithm,
803                    value: hazmat::EncapsulationKey::<P>::from(&typed).into_vec(),
804                },
805                // Every constructor, including `Default`, upholds the length invariant for
806                // the key's own parameter set, so this arm is unreachable; produce the
807                // default rather than panic.
808                Err(_) => EncapsulationKey::default(),
809            }
810        })
811    }
812}
813
814#[cfg(feature = "decapsulate")]
815impl Ciphertext {
816    /// Whether every padding bit is zero.
817    ///
818    /// [`DecapsulationKey::decapsulate`] rejects a ciphertext that fails this check. Parameter
819    /// sets whose `mt` is a multiple of eight have no padding, so this is always `true` for
820    /// them.
821    pub fn padding_is_zero(&self) -> bool {
822        with_params!(&self.algorithm, P, {
823            match hazmat::Ciphertext::<P>::from_slice(&self.value) {
824                Ok(ct) => ct.padding_is_zero(),
825                Err(_) => false,
826            }
827        })
828    }
829}
830
831impl DecapsulationKey {
832    /// The 32-byte seed this key was generated from.
833    ///
834    /// Knowing the seed is equivalent to knowing the whole private key, so treat it with the
835    /// same care. Storing the seed instead of the key trades a full key generation for a
836    /// factor of several hundred in storage.
837    pub fn seed(&self) -> &[u8] {
838        with_params!(&self.algorithm, P, { hazmat::seed_of::<P>(&self.value) })
839    }
840}
841
842#[cfg(feature = "decapsulate")]
843impl DecapsulationKey {
844    /// Recover the shared secret from a ciphertext.
845    ///
846    /// See [`Algorithm::decapsulate`] for what happens when the ciphertext does not decode.
847    pub fn decapsulate(&self, ciphertext: &Ciphertext) -> McElieceResult<SharedSecret> {
848        self.algorithm.decapsulate(self, ciphertext)
849    }
850
851    /// Precompute the key-derived part of decoding, for repeated decapsulation.
852    ///
853    /// About a quarter of a decapsulation depends only on the private key, not on the message.
854    /// Doing it once here rather than once per ciphertext is worth roughly a quarter off each
855    /// subsequent [`PreparedDecapsulationKey::decapsulate`], at the cost of holding the derived
856    /// material alongside the key. Decapsulating a single message is not worth preparing for.
857    pub fn prepare(&self) -> PreparedDecapsulationKey {
858        let (scale, valid, conds) = with_params!(&self.algorithm, P, {
859            let mut scale = vec![0; hazmat::decap::scale_words::<P>()];
860            let mut valid = vec![0u8; hazmat::decap::valid_bytes::<P>()];
861            let mut conds = vec![0u64; hazmat::decap::cond_words::<P>()];
862            hazmat::decap::prepare::<P>(&self.value, &mut scale, &mut valid, &mut conds);
863            (scale, valid, conds)
864        });
865        PreparedDecapsulationKey {
866            key: self.clone(),
867            scale,
868            valid,
869            conds,
870        }
871    }
872}
873
874/// A [`DecapsulationKey`] with the message-independent part of decoding already computed.
875///
876/// Produced by [`DecapsulationKey::prepare`]. The derived material is a function of the private
877/// key alone and is as sensitive as the key itself, so it is zeroized on drop and never
878/// serialized: store and transmit the [`DecapsulationKey`] and prepare again on the far side.
879#[cfg(feature = "decapsulate")]
880pub struct PreparedDecapsulationKey {
881    key: DecapsulationKey,
882    scale: Vec<hazmat::decap::PreparedWord>,
883    valid: Vec<u8>,
884    conds: Vec<u64>,
885}
886
887#[cfg(feature = "decapsulate")]
888impl PreparedDecapsulationKey {
889    /// The parameter set this key belongs to.
890    pub fn algorithm(&self) -> Algorithm {
891        self.key.algorithm
892    }
893
894    /// The key this was prepared from.
895    pub fn key(&self) -> &DecapsulationKey {
896        &self.key
897    }
898
899    /// Recover the shared secret from a ciphertext.
900    ///
901    /// Identical in result to [`DecapsulationKey::decapsulate`], including which ciphertexts are
902    /// rejected and the session key produced for those that fail to decode.
903    pub fn decapsulate(&self, ciphertext: &Ciphertext) -> McElieceResult<SharedSecret> {
904        let algorithm = self.key.algorithm;
905        if ciphertext.algorithm != algorithm {
906            return Err(Error::AlgorithmMismatch);
907        }
908        with_params!(&algorithm, P, {
909            if ciphertext.value.len() != P::CIPHERTEXT_LENGTH {
910                return Err(Error::InvalidCiphertextLength(ciphertext.value.len()));
911            }
912            let mut ss = vec![0u8; P::SHARED_SECRET_LENGTH];
913            if !hazmat::decap::decapsulate_prepared::<P>(
914                &mut ss,
915                &ciphertext.value,
916                &self.key.value,
917                &self.scale,
918                &self.valid,
919                &self.conds,
920            ) {
921                return Err(Error::CiphertextPadding);
922            }
923            Ok(SharedSecret {
924                algorithm,
925                value: ss,
926            })
927        })
928    }
929}
930
931#[cfg(feature = "decapsulate")]
932impl Drop for PreparedDecapsulationKey {
933    fn drop(&mut self) {
934        use zeroize::Zeroize;
935        self.scale.zeroize();
936        self.valid.zeroize();
937        self.conds.zeroize();
938    }
939}
940
941#[cfg(feature = "decapsulate")]
942impl core::fmt::Debug for PreparedDecapsulationKey {
943    /// Deliberately opaque: the derived material is as sensitive as the private key.
944    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
945        f.debug_struct("PreparedDecapsulationKey")
946            .field("algorithm", &self.key.algorithm)
947            .finish_non_exhaustive()
948    }
949}
950
951impl Algorithm {
952    /// The lowercase parameter set name, e.g. `mceliece6960119f`.
953    pub const fn name(&self) -> &'static str {
954        with_params!(self, P, { P::NAME })
955    }
956
957    /// The parameters underlying this parameter set.
958    pub const fn params(&self) -> AlgorithmParams {
959        with_params!(self, P, {
960            AlgorithmParams {
961                name: P::NAME,
962                m: P::M,
963                n: P::N,
964                t: P::T,
965                k: P::K,
966                semi_systematic: (P::MU, P::NU),
967                plaintext_confirmation: P::PC,
968                claimed_nist_level: P::CLAIMED_NIST_LEVEL,
969                in_nist_submission: P::STANDARDS.nist,
970                in_iso_standard: P::STANDARDS.iso,
971                encapsulation_key_length: P::PUBLIC_KEY_LENGTH,
972                decapsulation_key_length: P::SECRET_KEY_LENGTH,
973                ciphertext_length: P::CIPHERTEXT_LENGTH,
974                shared_secret_length: P::SHARED_SECRET_LENGTH,
975                seed_length: P::SEED_LENGTH,
976            }
977        })
978    }
979
980    /// Generate a key pair, drawing a fresh seed from `rng`.
981    #[cfg(feature = "keygen")]
982    pub fn generate_keypair(&self, rng: impl CryptoRng) -> (EncapsulationKey, DecapsulationKey) {
983        with_params!(self, P, {
984            let (ek, dk) = <P as Kem>::generate_keypair(rng);
985            (
986                EncapsulationKey {
987                    algorithm: *self,
988                    value: ek.into_vec(),
989                },
990                DecapsulationKey {
991                    algorithm: *self,
992                    value: dk.into_vec(),
993                },
994            )
995        })
996    }
997
998    /// Generate a key pair deterministically from a 32-byte seed.
999    ///
1000    /// The seed must come from a cryptographically secure source and is exactly as sensitive
1001    /// as the resulting private key.
1002    #[cfg(feature = "keygen")]
1003    pub fn generate_keypair_from_seed<B: AsRef<[u8]>>(
1004        &self,
1005        seed: B,
1006    ) -> McElieceResult<(EncapsulationKey, DecapsulationKey)> {
1007        with_params!(self, P, {
1008            let (ek, dk) = <P as Kem>::generate_keypair_from_seed(seed.as_ref())?;
1009            Ok((
1010                EncapsulationKey {
1011                    algorithm: *self,
1012                    value: ek.into_vec(),
1013                },
1014                DecapsulationKey {
1015                    algorithm: *self,
1016                    value: dk.into_vec(),
1017                },
1018            ))
1019        })
1020    }
1021
1022    /// Encapsulate to `key`, producing a ciphertext and the shared secret it transports.
1023    #[cfg(feature = "encapsulate")]
1024    pub fn encapsulate(
1025        &self,
1026        key: &EncapsulationKey,
1027        rng: impl CryptoRng,
1028    ) -> McElieceResult<(Ciphertext, SharedSecret)> {
1029        if key.algorithm != *self {
1030            return Err(Error::AlgorithmMismatch);
1031        }
1032        with_params!(self, P, {
1033            if key.value.len() != P::PUBLIC_KEY_LENGTH {
1034                return Err(Error::InvalidEncapsulationKeyLength(key.value.len()));
1035            }
1036            let mut ct = vec![0u8; P::CIPHERTEXT_LENGTH];
1037            let mut ss = vec![0u8; P::SHARED_SECRET_LENGTH];
1038            if !hazmat::encap::encapsulate::<P>(&mut ct, &mut ss, &key.value, rng) {
1039                return Err(Error::EncapsulationKeyPadding);
1040            }
1041            Ok((
1042                Ciphertext {
1043                    algorithm: *self,
1044                    value: ct,
1045                },
1046                SharedSecret {
1047                    algorithm: *self,
1048                    value: ss,
1049                },
1050            ))
1051        })
1052    }
1053
1054    /// Recover the shared secret from `ciphertext`.
1055    ///
1056    /// A ciphertext that does not decode is not reported as an error. Classic McEliece rejects
1057    /// implicitly: the returned secret is derived from the private key's rejection string, so
1058    /// it is unpredictable without the private key and identical every time the same bad
1059    /// ciphertext is presented.
1060    #[cfg(feature = "decapsulate")]
1061    pub fn decapsulate(
1062        &self,
1063        key: &DecapsulationKey,
1064        ciphertext: &Ciphertext,
1065    ) -> McElieceResult<SharedSecret> {
1066        if key.algorithm != *self || ciphertext.algorithm != *self {
1067            return Err(Error::AlgorithmMismatch);
1068        }
1069        with_params!(self, P, {
1070            if key.value.len() != P::SECRET_KEY_LENGTH {
1071                return Err(Error::InvalidDecapsulationKeyLength(key.value.len()));
1072            }
1073            if ciphertext.value.len() != P::CIPHERTEXT_LENGTH {
1074                return Err(Error::InvalidCiphertextLength(ciphertext.value.len()));
1075            }
1076            let mut ss = vec![0u8; P::SHARED_SECRET_LENGTH];
1077            if !hazmat::decap::decapsulate::<P>(&mut ss, &ciphertext.value, &key.value) {
1078                return Err(Error::CiphertextPadding);
1079            }
1080            Ok(SharedSecret {
1081                algorithm: *self,
1082                value: ss,
1083            })
1084        })
1085    }
1086
1087    /// Recover an encapsulation key from a decapsulation key.
1088    ///
1089    /// The key must belong to this parameter set. Parameter sets within a size family share
1090    /// their private-key length, so without this check a key from a sibling set would be
1091    /// accepted, rerunning key generation under the wrong variant and yielding a public key
1092    /// that does not match the private key.
1093    #[cfg(feature = "keygen")]
1094    pub fn encapsulation_key_from_decapsulation_key(
1095        &self,
1096        key: &DecapsulationKey,
1097    ) -> McElieceResult<EncapsulationKey> {
1098        if key.algorithm != *self {
1099            return Err(Error::AlgorithmMismatch);
1100        }
1101        Ok(EncapsulationKey::from(key))
1102    }
1103
1104    /// Parse bytes as an encapsulation key for this parameter set.
1105    pub fn encapsulation_key_from_bytes(&self, value: &[u8]) -> McElieceResult<EncapsulationKey> {
1106        with_params!(self, P, {
1107            hazmat::EncapsulationKey::<P>::from_slice(value).map(|key| EncapsulationKey {
1108                algorithm: *self,
1109                value: key.into_vec(),
1110            })
1111        })
1112    }
1113
1114    /// Parse bytes as a decapsulation key for this parameter set.
1115    pub fn decapsulation_key_from_bytes(&self, value: &[u8]) -> McElieceResult<DecapsulationKey> {
1116        with_params!(self, P, {
1117            hazmat::DecapsulationKey::<P>::from_slice(value).map(|key| DecapsulationKey {
1118                algorithm: *self,
1119                value: key.into_vec(),
1120            })
1121        })
1122    }
1123
1124    /// Parse bytes as a ciphertext for this parameter set.
1125    pub fn ciphertext_from_bytes(&self, value: &[u8]) -> McElieceResult<Ciphertext> {
1126        with_params!(self, P, {
1127            hazmat::Ciphertext::<P>::from_slice(value).map(|ct| Ciphertext {
1128                algorithm: *self,
1129                value: ct.into_vec(),
1130            })
1131        })
1132    }
1133
1134    /// Parse bytes as a shared secret for this parameter set.
1135    pub fn shared_secret_from_bytes(&self, value: &[u8]) -> McElieceResult<SharedSecret> {
1136        with_params!(self, P, {
1137            hazmat::SharedSecret::<P>::from_slice(value).map(|ss| SharedSecret {
1138                algorithm: *self,
1139                value: ss.into_vec(),
1140            })
1141        })
1142    }
1143}
1144
1145#[cfg(feature = "serde")]
1146impl serde::Serialize for Algorithm {
1147    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
1148    where
1149        S: serde::Serializer,
1150    {
1151        if s.is_human_readable() {
1152            s.serialize_str(self.name())
1153        } else {
1154            s.serialize_u8(u8::from(*self))
1155        }
1156    }
1157}
1158
1159#[cfg(feature = "serde")]
1160impl<'de> serde::Deserialize<'de> for Algorithm {
1161    fn deserialize<D>(d: D) -> Result<Algorithm, D::Error>
1162    where
1163        D: serde::Deserializer<'de>,
1164    {
1165        if d.is_human_readable() {
1166            let name = <String as serde::Deserialize>::deserialize(d)?;
1167            name.parse().map_err(serde::de::Error::custom)
1168        } else {
1169            let tag = <u8 as serde::Deserialize>::deserialize(d)?;
1170            tag.try_into().map_err(serde::de::Error::custom)
1171        }
1172    }
1173}
1174
1175#[cfg(all(
1176    test,
1177    feature = "keygen",
1178    feature = "encapsulate",
1179    feature = "decapsulate"
1180))]
1181#[allow(clippy::unwrap_used)]
1182mod tests {
1183
1184    /// A prepared key must be indistinguishable from the key it came from, including on the
1185    /// implicit-rejection path where a corrupted ciphertext still yields a reproducible secret.
1186    #[cfg(all(feature = "keygen", feature = "encapsulate", feature = "decapsulate"))]
1187    #[test]
1188    fn prepared_decapsulation_matches_the_plain_path() {
1189        use rand_core::{SeedableRng, UnwrapErr};
1190
1191        for &algorithm in Algorithm::enabled_algorithms() {
1192            let mut rng = UnwrapErr(rand_chacha::ChaCha8Rng::from_seed([29u8; 32]));
1193            let (ek, dk) = algorithm.generate_keypair(&mut rng);
1194            let prepared = dk.prepare();
1195            assert_eq!(prepared.algorithm(), algorithm);
1196            assert_eq!(prepared.key(), &dk);
1197
1198            let (ct, sent) = algorithm
1199                .encapsulate(&ek, &mut rng)
1200                .expect("a freshly generated key encapsulates");
1201            let direct = dk.decapsulate(&ct).expect("the ciphertext is well formed");
1202            let via_prepared = prepared.decapsulate(&ct).expect("likewise");
1203            assert_eq!(direct, sent, "{}", algorithm.name());
1204            assert_eq!(via_prepared, direct, "{} prepared", algorithm.name());
1205
1206            // Implicit rejection: flipping a syndrome bit must fail to decode, and both paths
1207            // must still agree on the substitute secret.
1208            let mut damaged = ct.clone();
1209            damaged.value[0] ^= 1;
1210            let direct = dk.decapsulate(&damaged);
1211            let via_prepared = prepared.decapsulate(&damaged);
1212            assert_eq!(direct, via_prepared, "{} rejected", algorithm.name());
1213            if let Ok(secret) = direct {
1214                assert_ne!(secret, sent, "{} rejection", algorithm.name());
1215            }
1216
1217            // A ciphertext from another parameter set must be refused, not decoded.
1218            let other = Algorithm::enabled_algorithms()
1219                .iter()
1220                .find(|&&a| a != algorithm)
1221                .copied();
1222            if let Some(other) = other {
1223                let (other_ek, _) = other.generate_keypair(&mut rng);
1224                let (other_ct, _) = other
1225                    .encapsulate(&other_ek, &mut rng)
1226                    .expect("a freshly generated key encapsulates");
1227                assert!(matches!(
1228                    prepared.decapsulate(&other_ct),
1229                    Err(Error::AlgorithmMismatch)
1230                ));
1231            }
1232        }
1233    }
1234    use super::*;
1235    use rand_core::SeedableRng;
1236
1237    #[test]
1238    fn every_algorithm_round_trips_through_its_public_conversions() {
1239        for &algorithm in Algorithm::enabled_algorithms() {
1240            let params = algorithm.params();
1241            assert_eq!(params.name, algorithm.name());
1242            assert_eq!(algorithm.to_string(), params.name);
1243            assert_eq!(params.name.parse::<Algorithm>().unwrap(), algorithm);
1244
1245            let id = u8::from(algorithm);
1246            assert_eq!(Algorithm::try_from(id).unwrap(), algorithm);
1247            assert_eq!(
1248                Algorithm::try_from(u16::from(algorithm)).unwrap(),
1249                algorithm
1250            );
1251            assert_eq!(
1252                Algorithm::try_from(u32::from(algorithm)).unwrap(),
1253                algorithm
1254            );
1255            assert_eq!(
1256                Algorithm::try_from(u64::from(algorithm)).unwrap(),
1257                algorithm
1258            );
1259            assert_eq!(
1260                Algorithm::try_from(usize::from(algorithm)).unwrap(),
1261                algorithm
1262            );
1263
1264            assert_eq!(params.k, params.n - params.m * params.t);
1265            assert_eq!(params.shared_secret_length, 32);
1266            assert_eq!(params.seed_length, 32);
1267            assert!(params.in_nist_submission || params.in_iso_standard);
1268            // Plaintext confirmation is exactly the 32-byte extension of the ciphertext.
1269            let syndrome_bytes = (params.m * params.t).div_ceil(8);
1270            assert_eq!(
1271                params.ciphertext_length,
1272                syndrome_bytes + if params.plaintext_confirmation { 32 } else { 0 }
1273            );
1274        }
1275
1276        assert!(Algorithm::try_from(0u8).is_err());
1277        assert!(Algorithm::try_from(200u8).is_err());
1278        assert!(Algorithm::try_from(300u16).is_err());
1279        assert!("not-an-algorithm".parse::<Algorithm>().is_err());
1280    }
1281
1282    #[test]
1283    fn the_standards_table_matches_the_published_lists() {
1284        for &algorithm in Algorithm::enabled_algorithms() {
1285            let params = algorithm.params();
1286            // The ISO standard covers every size except 3488, and adds the pc variants.
1287            assert_eq!(params.in_iso_standard, params.n != 3488, "{}", params.name);
1288            // The NIST submission covers every non-pc set.
1289            assert_eq!(
1290                params.in_nist_submission, !params.plaintext_confirmation,
1291                "{}",
1292                params.name
1293            );
1294        }
1295    }
1296
1297    #[test]
1298    fn value_types_validate_lengths_and_hide_secrets() {
1299        for &algorithm in Algorithm::enabled_algorithms() {
1300            let params = algorithm.params();
1301
1302            let ek =
1303                EncapsulationKey::from_bytes(algorithm, vec![0; params.encapsulation_key_length])
1304                    .unwrap();
1305            let dk =
1306                DecapsulationKey::from_bytes(algorithm, vec![0; params.decapsulation_key_length])
1307                    .unwrap();
1308            let ct = Ciphertext::from_bytes(algorithm, vec![0; params.ciphertext_length]).unwrap();
1309            let ss =
1310                SharedSecret::from_bytes(algorithm, vec![0; params.shared_secret_length]).unwrap();
1311
1312            assert_eq!(ek.algorithm(), algorithm);
1313            assert_eq!(ek.value(), ek.as_ref());
1314            assert_eq!(dk.algorithm(), algorithm);
1315            assert_eq!(ct.algorithm(), algorithm);
1316            assert_eq!(ss.algorithm(), algorithm);
1317
1318            assert!(EncapsulationKey::from_bytes(algorithm, []).is_err());
1319            assert!(DecapsulationKey::from_bytes(algorithm, []).is_err());
1320            assert!(Ciphertext::from_bytes(algorithm, []).is_err());
1321            assert!(SharedSecret::from_bytes(algorithm, []).is_err());
1322
1323            assert!(!format!("{dk:?}").contains("value"));
1324            assert!(!format!("{ss:?}").contains("value"));
1325            assert!(format!("{ek:?}").contains("value"));
1326        }
1327    }
1328
1329    #[test]
1330    fn the_dynamic_api_rejects_mismatched_algorithms() {
1331        let alg = Algorithm::enabled_algorithms()[0];
1332        let Some(&other) = Algorithm::enabled_algorithms().iter().find(|&&a| a != alg) else {
1333            // A build with a single parameter set has no mismatch to reject.
1334            return;
1335        };
1336
1337        let mut rng = rand_chacha::ChaCha8Rng::from_seed([5u8; 32]);
1338        let (ek, dk) = alg.generate_keypair(&mut rng);
1339        let (ct, _) = alg.encapsulate(&ek, &mut rng).unwrap();
1340
1341        assert_eq!(
1342            other.encapsulate(&ek, &mut rng).unwrap_err(),
1343            Error::AlgorithmMismatch
1344        );
1345        assert_eq!(
1346            other.decapsulate(&dk, &ct).unwrap_err(),
1347            Error::AlgorithmMismatch
1348        );
1349
1350        let foreign_ct =
1351            Ciphertext::from_bytes(other, vec![0; other.params().ciphertext_length]).unwrap();
1352        assert_eq!(
1353            dk.decapsulate(&foreign_ct).unwrap_err(),
1354            Error::AlgorithmMismatch
1355        );
1356    }
1357
1358    #[test]
1359    fn the_dynamic_api_rejects_default_values_without_panicking() {
1360        // `Default` values are well-formed all-zero values of the correct length, so every
1361        // operation completes without panicking: encapsulating to the zero key succeeds, and
1362        // decapsulating with the zero key degrades to implicit rejection. `seed` and
1363        // `prepare` used to panic on the old empty-value `Default`; they must not regress.
1364        let algorithm = Algorithm::default();
1365        let mut rng = rand_chacha::ChaCha8Rng::from_seed([6u8; 32]);
1366        let (ct, _ss) = algorithm
1367            .encapsulate(&EncapsulationKey::default(), &mut rng)
1368            .unwrap();
1369
1370        let key = DecapsulationKey::default();
1371        assert_eq!(key.seed(), [0u8; 32]);
1372        let plain = algorithm.decapsulate(&key, &ct).unwrap();
1373        let prepared = key.prepare();
1374        assert_eq!(prepared.decapsulate(&ct).unwrap(), plain);
1375        assert!(algorithm.decapsulate(&key, &Ciphertext::default()).is_ok());
1376
1377        // Hand-assembled wrong-length values still produce errors rather than panics.
1378        let empty = Ciphertext {
1379            algorithm,
1380            value: Vec::new(),
1381        };
1382        assert_eq!(
1383            algorithm.decapsulate(&key, &empty).unwrap_err(),
1384            Error::InvalidCiphertextLength(0)
1385        );
1386    }
1387
1388    #[test]
1389    #[cfg(feature = "mceliece6960119f")]
1390    fn the_recommended_algorithm_is_an_enabled_mceliece6_set() {
1391        assert_eq!(Algorithm::RECOMMENDED, Algorithm::McEliece6960119f);
1392        assert!(Algorithm::enabled_algorithms().contains(&Algorithm::RECOMMENDED));
1393    }
1394
1395    #[test]
1396    #[cfg(all(
1397        feature = "keygen",
1398        feature = "mceliece348864",
1399        feature = "mceliece348864f"
1400    ))]
1401    fn public_key_recovery_rejects_a_key_from_a_sibling_parameter_set() {
1402        // The `f` and non-`f` variants share their private-key length, so without the
1403        // algorithm check this would rerun key generation under the wrong variant and
1404        // silently return a public key that does not match the private key.
1405        let algorithm = Algorithm::McEliece348864;
1406        let sibling = DecapsulationKey::from_bytes(
1407            Algorithm::McEliece348864f,
1408            vec![0; Algorithm::McEliece348864f.params().decapsulation_key_length],
1409        )
1410        .unwrap();
1411        assert_eq!(
1412            algorithm
1413                .encapsulation_key_from_decapsulation_key(&sibling)
1414                .unwrap_err(),
1415            Error::AlgorithmMismatch
1416        );
1417    }
1418
1419    #[test]
1420    fn a_round_trip_recovers_the_shared_secret_and_rejection_is_stable() {
1421        let alg = Algorithm::enabled_algorithms()[0];
1422        let mut rng = rand_chacha::ChaCha8Rng::from_seed([13u8; 32]);
1423        let (ek, dk) = alg.generate_keypair(&mut rng);
1424
1425        let (ct, sent) = ek.encapsulate(&mut rng).unwrap();
1426        assert_eq!(dk.decapsulate(&ct).unwrap(), sent);
1427        assert_eq!(EncapsulationKey::from(&dk), ek);
1428
1429        let mut tampered = ct.clone();
1430        tampered.value[0] ^= 1;
1431        let first = dk.decapsulate(&tampered).unwrap();
1432        let second = dk.decapsulate(&tampered).unwrap();
1433        assert_eq!(first, second);
1434        assert_ne!(first, sent);
1435    }
1436
1437    #[test]
1438    fn deterministic_generation_validates_the_seed_length() {
1439        for &algorithm in Algorithm::enabled_algorithms() {
1440            let seed = vec![0xA5; algorithm.params().seed_length];
1441            let first = algorithm.generate_keypair_from_seed(&seed).unwrap();
1442            let second = algorithm.generate_keypair_from_seed(&seed).unwrap();
1443            assert_eq!(first, second);
1444
1445            assert_eq!(
1446                algorithm
1447                    .generate_keypair_from_seed(&seed[..seed.len() - 1])
1448                    .unwrap_err(),
1449                Error::InvalidSeedLength(31)
1450            );
1451            let mut long = seed;
1452            long.push(0);
1453            assert_eq!(
1454                algorithm.generate_keypair_from_seed(long).unwrap_err(),
1455                Error::InvalidSeedLength(33)
1456            );
1457        }
1458    }
1459
1460    /// The padding accessors are how a caller inspects the *narrowly decoded* rejection before
1461    /// it happens, and `mceliece6960119` is the one standardized set that has padding at all.
1462    #[cfg(all(feature = "keygen", feature = "encapsulate"))]
1463    #[test]
1464    fn padding_accessors_report_both_outcomes() {
1465        for &algorithm in Algorithm::enabled_algorithms() {
1466            let mut rng = rand_chacha::ChaCha8Rng::from_seed([23u8; 32]);
1467            let (ek, _) = algorithm.generate_keypair(&mut rng);
1468            let (ct, _) = algorithm.encapsulate(&ek, &mut rng).unwrap();
1469
1470            assert!(ek.padding_is_zero(), "{} fresh key", algorithm.name());
1471            assert!(
1472                ct.padding_is_zero(),
1473                "{} fresh ciphertext",
1474                algorithm.name()
1475            );
1476
1477            // Setting every padding bit is only detectable where padding exists.
1478            let has_padding = algorithm.params().k % 8 != 0;
1479            let mut damaged = ek.clone();
1480            let last = damaged.value.len() - 1;
1481            damaged.value[last] = 0xFF;
1482            assert_eq!(
1483                damaged.padding_is_zero(),
1484                !has_padding,
1485                "{} damaged key",
1486                algorithm.name()
1487            );
1488
1489            // The padding sits at the end of the syndrome, which for a `pc` set is not the end
1490            // of the ciphertext: the plaintext-confirmation hash follows it.
1491            let params = algorithm.params();
1492            let syndrome_bytes = (params.m * params.t).div_ceil(8);
1493            let ciphertext_has_padding = params.m * params.t % 8 != 0;
1494            let mut damaged = ct.clone();
1495            damaged.value[syndrome_bytes - 1] = 0xFF;
1496            assert_eq!(
1497                damaged.padding_is_zero(),
1498                !ciphertext_has_padding,
1499                "{} damaged ciphertext",
1500                algorithm.name()
1501            );
1502
1503            // A value of the wrong length belongs to no parameter set and cannot be inspected.
1504            let mut truncated = ek;
1505            truncated.value.truncate(1);
1506            assert!(
1507                !truncated.padding_is_zero(),
1508                "{} short key",
1509                algorithm.name()
1510            );
1511            let mut truncated = ct;
1512            truncated.value.truncate(1);
1513            assert!(
1514                !truncated.padding_is_zero(),
1515                "{} short ciphertext",
1516                algorithm.name()
1517            );
1518        }
1519    }
1520
1521    #[cfg(feature = "serde")]
1522    mod serde_tests {
1523        use super::*;
1524
1525        /// Deserialization is the crate's exposure to input it did not produce, so the paths
1526        /// that reject malformed encodings need exercising as much as the round trip does.
1527        #[cfg(all(feature = "keygen", feature = "encapsulate"))]
1528        #[test]
1529        fn deserialization_rejects_malformed_encodings() {
1530            let alg = Algorithm::enabled_algorithms()[0];
1531            let mut rng = rand_chacha::ChaCha8Rng::from_seed([17u8; 32]);
1532            let (ek, _) = alg.generate_keypair(&mut rng);
1533            let encoded = serde_json::to_string(&ek).unwrap();
1534
1535            // A repeated field must be refused rather than silently taking one of the two.
1536            let doubled_algorithm = encoded.replacen('{', r#"{"algorithm":"mceliece348864","#, 1);
1537            assert!(serde_json::from_str::<EncapsulationKey>(&doubled_algorithm).is_err());
1538            let doubled_value = encoded.replacen('{', r#"{"value":"00","#, 1);
1539            assert!(serde_json::from_str::<EncapsulationKey>(&doubled_value).is_err());
1540
1541            // So must a missing field, an unknown one, and a value that is not a hex string.
1542            assert!(serde_json::from_str::<EncapsulationKey>(r#"{"value":"00"}"#).is_err());
1543            assert!(
1544                serde_json::from_str::<EncapsulationKey>(&encoded.replacen(
1545                    '{',
1546                    r#"{"nope":1,"#,
1547                    1
1548                ))
1549                .is_err()
1550            );
1551            assert!(
1552                serde_json::from_str::<EncapsulationKey>(
1553                    r#"{"algorithm":"mceliece348864","value":"zz"}"#
1554                )
1555                .is_err()
1556            );
1557
1558            // A shape that is not a map at all, and a value of the wrong length for its set.
1559            assert!(serde_json::from_str::<EncapsulationKey>("[]").is_err());
1560            assert!(
1561                serde_json::from_str::<EncapsulationKey>(
1562                    r#"{"algorithm":"mceliece348864","value":"00ff"}"#
1563                )
1564                .is_err()
1565            );
1566        }
1567
1568        macro_rules! serde_round_trip {
1569            ($name:ident, $ser:path, $de:path) => {
1570                #[test]
1571                fn $name() {
1572                    let alg = Algorithm::enabled_algorithms()[0];
1573                    let mut rng = rand_chacha::ChaCha8Rng::from_seed([3u8; 32]);
1574                    let (ek, dk) = alg.generate_keypair(&mut rng);
1575                    let (ct, ss) = alg.encapsulate(&ek, &mut rng).unwrap();
1576
1577                    let encoded = $ser(&ek).unwrap();
1578                    let decoded: EncapsulationKey = $de(&encoded).unwrap();
1579                    assert_eq!(decoded, ek);
1580
1581                    let encoded = $ser(&dk).unwrap();
1582                    let decoded: DecapsulationKey = $de(&encoded).unwrap();
1583                    assert_eq!(decoded, dk);
1584
1585                    let encoded = $ser(&ct).unwrap();
1586                    let decoded: Ciphertext = $de(&encoded).unwrap();
1587                    assert_eq!(decoded, ct);
1588
1589                    let encoded = $ser(&ss).unwrap();
1590                    let decoded: SharedSecret = $de(&encoded).unwrap();
1591                    assert_eq!(decoded, ss);
1592                }
1593            };
1594        }
1595
1596        serde_round_trip!(json, serde_json::to_string, serde_json::from_str);
1597        serde_round_trip!(toml, toml::to_string, toml::from_str);
1598        serde_round_trip!(yaml, yaml_serde::to_string, yaml_serde::from_str);
1599        serde_round_trip!(bare, serde_bare::to_vec, serde_bare::from_slice);
1600        serde_round_trip!(cbor, serde_cbor_2::to_vec, serde_cbor_2::from_slice);
1601        serde_round_trip!(postcard, postcard::to_stdvec, postcard::from_bytes);
1602    }
1603}