1#![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#[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
240macro_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
341macro_rules! declare_algorithms {
343 ($(
344 $(#[$meta:meta])*
345 $feature:literal => $variant:ident, $id:literal;
346 )+) => {
347 #[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 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" => McEliece348864, 1;
414 "mceliece348864f" => McEliece348864f, 2;
416 "mceliece460896" => McEliece460896, 3;
418 "mceliece460896f" => McEliece460896f, 4;
420 "mceliece460896pc" => McEliece460896pc, 5;
422 "mceliece460896pcf" => McEliece460896pcf, 6;
424 "mceliece6688128" => McEliece6688128, 7;
426 "mceliece6688128f" => McEliece6688128f, 8;
428 "mceliece6688128pc" => McEliece6688128pc, 9;
430 "mceliece6688128pcf" => McEliece6688128pcf, 10;
432 "mceliece6960119" => McEliece6960119, 11;
434 "mceliece6960119f" => McEliece6960119f, 12;
436 "mceliece6960119pc" => McEliece6960119pc, 13;
438 "mceliece6960119pcf" => McEliece6960119pcf, 14;
440 "mceliece8192128" => McEliece8192128, 15;
442 "mceliece8192128f" => McEliece8192128f, 16;
444 "mceliece8192128pc" => McEliece8192128pc, 17;
446 "mceliece8192128pcf" => McEliece8192128pcf, 18;
448}
449
450impl Algorithm {
451 #[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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
509#[non_exhaustive]
510pub struct AlgorithmParams {
511 pub name: &'static str,
513 pub m: usize,
515 pub n: usize,
517 pub t: usize,
519 pub k: usize,
521 pub semi_systematic: (usize, usize),
523 pub plaintext_confirmation: bool,
525 pub claimed_nist_level: usize,
527 pub in_nist_submission: bool,
529 pub in_iso_standard: bool,
531 pub encapsulation_key_length: usize,
533 pub decapsulation_key_length: usize,
535 pub ciphertext_length: usize,
537 pub shared_secret_length: usize,
539 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 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 pub fn algorithm(&self) -> Algorithm {
687 self.algorithm
688 }
689
690 pub fn value(&self) -> &[u8] {
692 &self.value
693 }
694
695 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 EncapsulationKey, encapsulation_key_from_bytes, secret = false, length = PUBLIC_KEY_LENGTH
744}
745
746value_type! {
747 DecapsulationKey, decapsulation_key_from_bytes, secret = true, length = SECRET_KEY_LENGTH
749}
750
751value_type! {
752 Ciphertext, ciphertext_from_bytes, secret = false, length = CIPHERTEXT_LENGTH
754}
755
756value_type! {
757 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 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 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 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 Err(_) => EncapsulationKey::default(),
819 }
820 })
821 }
822}
823
824#[cfg(feature = "decapsulate")]
825impl Ciphertext {
826 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 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 pub fn decapsulate(&self, ciphertext: &Ciphertext) -> McElieceResult<SharedSecret> {
858 self.algorithm.decapsulate(self, ciphertext)
859 }
860
861 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#[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 pub fn algorithm(&self) -> Algorithm {
901 self.key.algorithm
902 }
903
904 pub fn key(&self) -> &DecapsulationKey {
906 &self.key
907 }
908
909 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 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 pub const fn name(&self) -> &'static str {
964 with_params!(self, P, { P::NAME })
965 }
966
967 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 #[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 #[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 #[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 #[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 #[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 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 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 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 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 #[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 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 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 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 assert_eq!(params.in_iso_standard, params.n != 3488, "{}", params.name);
1298 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 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 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 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 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 #[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 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 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 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 #[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 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 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 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}