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