1#![warn(
154 missing_docs,
155 missing_debug_implementations,
156 missing_copy_implementations,
157 trivial_casts,
158 trivial_numeric_casts,
159 unused,
160 clippy::mod_module_files
161)]
162#![deny(clippy::unwrap_used)]
163
164#[cfg(not(any(
165 feature = "mceliece348864",
166 feature = "mceliece348864f",
167 feature = "mceliece460896",
168 feature = "mceliece460896f",
169 feature = "mceliece460896pc",
170 feature = "mceliece460896pcf",
171 feature = "mceliece6688128",
172 feature = "mceliece6688128f",
173 feature = "mceliece6688128pc",
174 feature = "mceliece6688128pcf",
175 feature = "mceliece6960119",
176 feature = "mceliece6960119f",
177 feature = "mceliece6960119pc",
178 feature = "mceliece6960119pcf",
179 feature = "mceliece8192128",
180 feature = "mceliece8192128f",
181 feature = "mceliece8192128pc",
182 feature = "mceliece8192128pcf",
183)))]
184compile_error!("no Classic McEliece parameter set feature is enabled");
185
186#[cfg(not(any(feature = "keygen", feature = "encapsulate", feature = "decapsulate")))]
187compile_error!(
188 "no Classic McEliece operation feature is enabled; \
189 select at least one of `keygen`, `encapsulate` or `decapsulate`"
190);
191
192#[cfg(all(
200 doctest,
201 feature = "hazmat",
202 feature = "kem",
203 feature = "mceliece348864f",
204 feature = "mceliece460896f",
205 feature = "mceliece6960119f",
206 feature = "mceliece8192128f"
207))]
208#[doc = include_str!("../README.md")]
209pub struct ReadmeExamples;
210
211mod error;
212pub use error::*;
213
214#[cfg(feature = "kem")]
215pub mod kem;
216
217#[cfg(feature = "hazmat")]
218pub mod hazmat;
219#[cfg(not(feature = "hazmat"))]
220mod hazmat;
221
222use ctutils::{Choice, CtEq};
223#[cfg(feature = "keygen")]
224use hazmat::Kem;
225use hazmat::Params;
226#[cfg(any(feature = "keygen", feature = "encapsulate"))]
227use rand_core::CryptoRng;
228use zeroize::{Zeroize, ZeroizeOnDrop};
229
230macro_rules! with_params {
235 ($alg:expr, $p:ident, $body:block) => {
236 match $alg {
237 #[cfg(feature = "mceliece348864")]
238 Algorithm::McEliece348864 => {
239 type $p = hazmat::McEliece348864;
240 $body
241 }
242 #[cfg(feature = "mceliece348864f")]
243 Algorithm::McEliece348864f => {
244 type $p = hazmat::McEliece348864f;
245 $body
246 }
247 #[cfg(feature = "mceliece460896")]
248 Algorithm::McEliece460896 => {
249 type $p = hazmat::McEliece460896;
250 $body
251 }
252 #[cfg(feature = "mceliece460896f")]
253 Algorithm::McEliece460896f => {
254 type $p = hazmat::McEliece460896f;
255 $body
256 }
257 #[cfg(feature = "mceliece460896pc")]
258 Algorithm::McEliece460896pc => {
259 type $p = hazmat::McEliece460896pc;
260 $body
261 }
262 #[cfg(feature = "mceliece460896pcf")]
263 Algorithm::McEliece460896pcf => {
264 type $p = hazmat::McEliece460896pcf;
265 $body
266 }
267 #[cfg(feature = "mceliece6688128")]
268 Algorithm::McEliece6688128 => {
269 type $p = hazmat::McEliece6688128;
270 $body
271 }
272 #[cfg(feature = "mceliece6688128f")]
273 Algorithm::McEliece6688128f => {
274 type $p = hazmat::McEliece6688128f;
275 $body
276 }
277 #[cfg(feature = "mceliece6688128pc")]
278 Algorithm::McEliece6688128pc => {
279 type $p = hazmat::McEliece6688128pc;
280 $body
281 }
282 #[cfg(feature = "mceliece6688128pcf")]
283 Algorithm::McEliece6688128pcf => {
284 type $p = hazmat::McEliece6688128pcf;
285 $body
286 }
287 #[cfg(feature = "mceliece6960119")]
288 Algorithm::McEliece6960119 => {
289 type $p = hazmat::McEliece6960119;
290 $body
291 }
292 #[cfg(feature = "mceliece6960119f")]
293 Algorithm::McEliece6960119f => {
294 type $p = hazmat::McEliece6960119f;
295 $body
296 }
297 #[cfg(feature = "mceliece6960119pc")]
298 Algorithm::McEliece6960119pc => {
299 type $p = hazmat::McEliece6960119pc;
300 $body
301 }
302 #[cfg(feature = "mceliece6960119pcf")]
303 Algorithm::McEliece6960119pcf => {
304 type $p = hazmat::McEliece6960119pcf;
305 $body
306 }
307 #[cfg(feature = "mceliece8192128")]
308 Algorithm::McEliece8192128 => {
309 type $p = hazmat::McEliece8192128;
310 $body
311 }
312 #[cfg(feature = "mceliece8192128f")]
313 Algorithm::McEliece8192128f => {
314 type $p = hazmat::McEliece8192128f;
315 $body
316 }
317 #[cfg(feature = "mceliece8192128pc")]
318 Algorithm::McEliece8192128pc => {
319 type $p = hazmat::McEliece8192128pc;
320 $body
321 }
322 #[cfg(feature = "mceliece8192128pcf")]
323 Algorithm::McEliece8192128pcf => {
324 type $p = hazmat::McEliece8192128pcf;
325 $body
326 }
327 }
328 };
329}
330
331macro_rules! declare_algorithms {
333 ($(
334 $(#[$meta:meta])*
335 $feature:literal => $variant:ident, $id:literal;
336 )+) => {
337 #[derive(Debug, Clone, Copy, PartialEq, Eq, Ord, PartialOrd, Hash)]
339 #[non_exhaustive]
340 pub enum Algorithm {
341 $(
342 $(#[$meta])*
343 #[cfg(feature = $feature)]
344 $variant,
345 )+
346 }
347
348 impl Algorithm {
349 pub const fn enabled_algorithms() -> &'static [Algorithm] {
351 &[
352 $(
353 #[cfg(feature = $feature)]
354 Self::$variant,
355 )+
356 ]
357 }
358 }
359
360 impl From<Algorithm> for u8 {
361 fn from(algorithm: Algorithm) -> u8 {
362 match algorithm {
363 $(
364 #[cfg(feature = $feature)]
365 Algorithm::$variant => $id,
366 )+
367 }
368 }
369 }
370
371 impl TryFrom<u8> for Algorithm {
372 type Error = Error;
373
374 fn try_from(value: u8) -> Result<Self, Self::Error> {
375 match value {
376 $(
377 #[cfg(feature = $feature)]
378 $id => Ok(Algorithm::$variant),
379 )+
380 _ => Err(Error::UnsupportedAlgorithm),
381 }
382 }
383 }
384
385 impl core::str::FromStr for Algorithm {
386 type Err = Error;
387
388 fn from_str(s: &str) -> Result<Self, Self::Err> {
389 match s {
390 $(
391 #[cfg(feature = $feature)]
392 $feature => Ok(Algorithm::$variant),
393 )+
394 _ => Err(Error::UnsupportedAlgorithm),
395 }
396 }
397 }
398 };
399}
400
401declare_algorithms! {
402 "mceliece348864" => McEliece348864, 1;
404 "mceliece348864f" => McEliece348864f, 2;
406 "mceliece460896" => McEliece460896, 3;
408 "mceliece460896f" => McEliece460896f, 4;
410 "mceliece460896pc" => McEliece460896pc, 5;
412 "mceliece460896pcf" => McEliece460896pcf, 6;
414 "mceliece6688128" => McEliece6688128, 7;
416 "mceliece6688128f" => McEliece6688128f, 8;
418 "mceliece6688128pc" => McEliece6688128pc, 9;
420 "mceliece6688128pcf" => McEliece6688128pcf, 10;
422 "mceliece6960119" => McEliece6960119, 11;
424 "mceliece6960119f" => McEliece6960119f, 12;
426 "mceliece6960119pc" => McEliece6960119pc, 13;
428 "mceliece6960119pcf" => McEliece6960119pcf, 14;
430 "mceliece8192128" => McEliece8192128, 15;
432 "mceliece8192128f" => McEliece8192128f, 16;
434 "mceliece8192128pc" => McEliece8192128pc, 17;
436 "mceliece8192128pcf" => McEliece8192128pcf, 18;
438}
439
440impl Algorithm {
441 #[cfg(feature = "mceliece6960119f")]
452 pub const RECOMMENDED: Algorithm = Algorithm::McEliece6960119f;
453}
454
455impl Default for Algorithm {
456 fn default() -> Self {
457 Self::enabled_algorithms()[0]
458 }
459}
460
461impl core::fmt::Display for Algorithm {
462 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
463 f.write_str(self.name())
464 }
465}
466
467impl CtEq for Algorithm {
468 fn ct_eq(&self, other: &Self) -> Choice {
469 u8::from(*self).ct_eq(&u8::from(*other))
470 }
471}
472
473macro_rules! widening_conversions {
474 ($($ty:ty),+) => {
475 $(
476 impl From<Algorithm> for $ty {
477 fn from(algorithm: Algorithm) -> Self {
478 u8::from(algorithm) as $ty
479 }
480 }
481
482 impl TryFrom<$ty> for Algorithm {
483 type Error = Error;
484
485 fn try_from(value: $ty) -> Result<Self, Self::Error> {
486 u8::try_from(value)
487 .map_err(|_| Error::UnsupportedAlgorithm)?
488 .try_into()
489 }
490 }
491 )+
492 };
493}
494
495widening_conversions!(u16, u32, u64, u128, usize);
496
497#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
499#[non_exhaustive]
500pub struct AlgorithmParams {
501 pub name: &'static str,
503 pub m: usize,
505 pub n: usize,
507 pub t: usize,
509 pub k: usize,
511 pub semi_systematic: (usize, usize),
513 pub plaintext_confirmation: bool,
515 pub claimed_nist_level: usize,
517 pub in_nist_submission: bool,
519 pub in_iso_standard: bool,
521 pub encapsulation_key_length: usize,
523 pub decapsulation_key_length: usize,
525 pub ciphertext_length: usize,
527 pub shared_secret_length: usize,
529 pub seed_length: usize,
531}
532
533macro_rules! serde_impl {
534 ($name:ident, $from_method:ident) => {
535 #[cfg(feature = "serde")]
536 impl serde::Serialize for $name {
537 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
538 where
539 S: serde::Serializer,
540 {
541 if s.is_human_readable() {
542 use serde::ser::SerializeStruct;
543
544 let mut map = s.serialize_struct(stringify!($name), 2)?;
545 map.serialize_field("algorithm", self.algorithm.name())?;
546 map.serialize_field("value", &hex::encode(&self.value))?;
547 map.end()
548 } else {
549 let mut seq = Vec::with_capacity(self.value.len() + 1);
550 seq.push(u8::from(self.algorithm));
551 seq.extend_from_slice(&self.value);
552 s.serialize_bytes(&seq)
553 }
554 }
555 }
556
557 #[cfg(feature = "serde")]
558 impl<'de> serde::Deserialize<'de> for $name {
559 fn deserialize<D>(d: D) -> Result<Self, D::Error>
560 where
561 D: serde::Deserializer<'de>,
562 {
563 if d.is_human_readable() {
564 #[derive(serde::Deserialize)]
565 #[serde(field_identifier, rename_all = "snake_case")]
566 enum Field {
567 Algorithm,
568 Value,
569 }
570
571 struct StructVisitor;
572
573 impl<'de> serde::de::Visitor<'de> for StructVisitor {
574 type Value = $name;
575
576 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
577 write!(f, "a struct with an algorithm and a hex value")
578 }
579
580 fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
581 where
582 A: serde::de::MapAccess<'de>,
583 {
584 let mut algorithm = Option::<Algorithm>::None;
585 let mut value = Option::<String>::None;
586 while let Some(key) = map.next_key()? {
587 match key {
588 Field::Algorithm => {
589 if algorithm.is_some() {
590 return Err(serde::de::Error::duplicate_field(
591 "algorithm",
592 ));
593 }
594 algorithm = Some(map.next_value()?);
595 }
596 Field::Value => {
597 if value.is_some() {
598 return Err(serde::de::Error::duplicate_field("value"));
599 }
600 value = Some(map.next_value()?);
601 }
602 }
603 }
604
605 let algorithm = algorithm
606 .ok_or_else(|| serde::de::Error::missing_field("algorithm"))?;
607 let value =
608 value.ok_or_else(|| serde::de::Error::missing_field("value"))?;
609 let value = hex::decode(&value).map_err(serde::de::Error::custom)?;
610 algorithm
611 .$from_method(&value)
612 .map_err(serde::de::Error::custom)
613 }
614 }
615
616 const FIELDS: &[&str] = &["algorithm", "value"];
617 d.deserialize_struct(stringify!($name), FIELDS, StructVisitor)
618 } else {
619 struct BytesVisitor;
620
621 impl<'de> serde::de::Visitor<'de> for BytesVisitor {
622 type Value = $name;
623
624 fn expecting(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
625 write!(f, "a byte sequence")
626 }
627
628 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
629 where
630 E: serde::de::Error,
631 {
632 let (tag, value) = v.split_first().ok_or_else(|| {
633 serde::de::Error::custom(Error::UnsupportedAlgorithm)
634 })?;
635 let algorithm =
636 Algorithm::try_from(*tag).map_err(serde::de::Error::custom)?;
637 algorithm
638 .$from_method(value)
639 .map_err(serde::de::Error::custom)
640 }
641 }
642
643 d.deserialize_bytes(BytesVisitor)
644 }
645 }
646 }
647 };
648}
649
650macro_rules! value_type {
651 (
652 $(#[$meta:meta])*
653 $name:ident, $from_method:ident, secret = $secret:literal, length = $length:ident
654 ) => {
655 $(#[$meta])*
656 #[derive(Clone)]
657 pub struct $name {
658 pub(crate) algorithm: Algorithm,
659 pub(crate) value: Vec<u8>,
660 }
661
662 impl Default for $name {
663 fn default() -> Self {
668 let algorithm = Algorithm::default();
669 let value = with_params!(&algorithm, P, { vec![0u8; P::$length] });
670 Self { algorithm, value }
671 }
672 }
673
674 impl $name {
675 pub fn algorithm(&self) -> Algorithm {
677 self.algorithm
678 }
679
680 pub fn value(&self) -> &[u8] {
682 &self.value
683 }
684
685 pub fn from_bytes<B: AsRef<[u8]>>(
687 algorithm: Algorithm,
688 value: B,
689 ) -> McElieceResult<Self> {
690 algorithm.$from_method(value.as_ref())
691 }
692 }
693
694 impl AsRef<[u8]> for $name {
695 fn as_ref(&self) -> &[u8] {
696 &self.value
697 }
698 }
699
700 impl CtEq for $name {
701 fn ct_eq(&self, other: &Self) -> Choice {
702 self.algorithm.ct_eq(&other.algorithm)
703 & self.value.as_slice().ct_eq(other.value.as_slice())
704 }
705 }
706
707 impl PartialEq for $name {
708 fn eq(&self, other: &Self) -> bool {
709 bool::from(self.ct_eq(other))
710 }
711 }
712
713 impl Eq for $name {}
714
715 impl core::fmt::Debug for $name {
716 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
717 let mut out = f.debug_struct(stringify!($name));
718 out.field("algorithm", &self.algorithm);
719 if $secret {
720 out.finish_non_exhaustive()
721 } else {
722 out.field("value", &self.value).finish()
723 }
724 }
725 }
726
727 serde_impl!($name, $from_method);
728 };
729}
730
731value_type! {
732 EncapsulationKey, encapsulation_key_from_bytes, secret = false, length = PUBLIC_KEY_LENGTH
734}
735
736value_type! {
737 DecapsulationKey, decapsulation_key_from_bytes, secret = true, length = SECRET_KEY_LENGTH
739}
740
741value_type! {
742 Ciphertext, ciphertext_from_bytes, secret = false, length = CIPHERTEXT_LENGTH
744}
745
746value_type! {
747 SharedSecret, shared_secret_from_bytes, secret = true, length = SHARED_SECRET_LENGTH
749}
750
751macro_rules! zeroize_on_drop {
752 ($name:ident) => {
753 impl Zeroize for $name {
754 fn zeroize(&mut self) {
755 self.value.zeroize();
756 }
757 }
758
759 impl ZeroizeOnDrop for $name {}
760
761 impl Drop for $name {
762 fn drop(&mut self) {
763 self.zeroize();
764 }
765 }
766 };
767}
768
769zeroize_on_drop!(DecapsulationKey);
770zeroize_on_drop!(SharedSecret);
771
772#[cfg(feature = "encapsulate")]
773impl EncapsulationKey {
774 pub fn padding_is_zero(&self) -> bool {
779 with_params!(&self.algorithm, P, {
780 match hazmat::EncapsulationKey::<P>::from_slice(&self.value) {
781 Ok(key) => key.padding_is_zero(),
782 Err(_) => false,
783 }
784 })
785 }
786
787 pub fn encapsulate(&self, rng: impl CryptoRng) -> McElieceResult<(Ciphertext, SharedSecret)> {
789 self.algorithm.encapsulate(self, rng)
790 }
791}
792
793#[cfg(feature = "keygen")]
794impl From<&DecapsulationKey> for EncapsulationKey {
795 fn from(secret: &DecapsulationKey) -> Self {
799 with_params!(&secret.algorithm, P, {
800 match hazmat::DecapsulationKey::<P>::from_slice(&secret.value) {
801 Ok(typed) => EncapsulationKey {
802 algorithm: secret.algorithm,
803 value: hazmat::EncapsulationKey::<P>::from(&typed).into_vec(),
804 },
805 Err(_) => EncapsulationKey::default(),
809 }
810 })
811 }
812}
813
814#[cfg(feature = "decapsulate")]
815impl Ciphertext {
816 pub fn padding_is_zero(&self) -> bool {
822 with_params!(&self.algorithm, P, {
823 match hazmat::Ciphertext::<P>::from_slice(&self.value) {
824 Ok(ct) => ct.padding_is_zero(),
825 Err(_) => false,
826 }
827 })
828 }
829}
830
831impl DecapsulationKey {
832 pub fn seed(&self) -> &[u8] {
838 with_params!(&self.algorithm, P, { hazmat::seed_of::<P>(&self.value) })
839 }
840}
841
842#[cfg(feature = "decapsulate")]
843impl DecapsulationKey {
844 pub fn decapsulate(&self, ciphertext: &Ciphertext) -> McElieceResult<SharedSecret> {
848 self.algorithm.decapsulate(self, ciphertext)
849 }
850
851 pub fn prepare(&self) -> PreparedDecapsulationKey {
858 let (scale, valid, conds) = with_params!(&self.algorithm, P, {
859 let mut scale = vec![0; hazmat::decap::scale_words::<P>()];
860 let mut valid = vec![0u8; hazmat::decap::valid_bytes::<P>()];
861 let mut conds = vec![0u64; hazmat::decap::cond_words::<P>()];
862 hazmat::decap::prepare::<P>(&self.value, &mut scale, &mut valid, &mut conds);
863 (scale, valid, conds)
864 });
865 PreparedDecapsulationKey {
866 key: self.clone(),
867 scale,
868 valid,
869 conds,
870 }
871 }
872}
873
874#[cfg(feature = "decapsulate")]
880pub struct PreparedDecapsulationKey {
881 key: DecapsulationKey,
882 scale: Vec<hazmat::decap::PreparedWord>,
883 valid: Vec<u8>,
884 conds: Vec<u64>,
885}
886
887#[cfg(feature = "decapsulate")]
888impl PreparedDecapsulationKey {
889 pub fn algorithm(&self) -> Algorithm {
891 self.key.algorithm
892 }
893
894 pub fn key(&self) -> &DecapsulationKey {
896 &self.key
897 }
898
899 pub fn decapsulate(&self, ciphertext: &Ciphertext) -> McElieceResult<SharedSecret> {
904 let algorithm = self.key.algorithm;
905 if ciphertext.algorithm != algorithm {
906 return Err(Error::AlgorithmMismatch);
907 }
908 with_params!(&algorithm, P, {
909 if ciphertext.value.len() != P::CIPHERTEXT_LENGTH {
910 return Err(Error::InvalidCiphertextLength(ciphertext.value.len()));
911 }
912 let mut ss = vec![0u8; P::SHARED_SECRET_LENGTH];
913 if !hazmat::decap::decapsulate_prepared::<P>(
914 &mut ss,
915 &ciphertext.value,
916 &self.key.value,
917 &self.scale,
918 &self.valid,
919 &self.conds,
920 ) {
921 return Err(Error::CiphertextPadding);
922 }
923 Ok(SharedSecret {
924 algorithm,
925 value: ss,
926 })
927 })
928 }
929}
930
931#[cfg(feature = "decapsulate")]
932impl Drop for PreparedDecapsulationKey {
933 fn drop(&mut self) {
934 use zeroize::Zeroize;
935 self.scale.zeroize();
936 self.valid.zeroize();
937 self.conds.zeroize();
938 }
939}
940
941#[cfg(feature = "decapsulate")]
942impl core::fmt::Debug for PreparedDecapsulationKey {
943 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
945 f.debug_struct("PreparedDecapsulationKey")
946 .field("algorithm", &self.key.algorithm)
947 .finish_non_exhaustive()
948 }
949}
950
951impl Algorithm {
952 pub const fn name(&self) -> &'static str {
954 with_params!(self, P, { P::NAME })
955 }
956
957 pub const fn params(&self) -> AlgorithmParams {
959 with_params!(self, P, {
960 AlgorithmParams {
961 name: P::NAME,
962 m: P::M,
963 n: P::N,
964 t: P::T,
965 k: P::K,
966 semi_systematic: (P::MU, P::NU),
967 plaintext_confirmation: P::PC,
968 claimed_nist_level: P::CLAIMED_NIST_LEVEL,
969 in_nist_submission: P::STANDARDS.nist,
970 in_iso_standard: P::STANDARDS.iso,
971 encapsulation_key_length: P::PUBLIC_KEY_LENGTH,
972 decapsulation_key_length: P::SECRET_KEY_LENGTH,
973 ciphertext_length: P::CIPHERTEXT_LENGTH,
974 shared_secret_length: P::SHARED_SECRET_LENGTH,
975 seed_length: P::SEED_LENGTH,
976 }
977 })
978 }
979
980 #[cfg(feature = "keygen")]
982 pub fn generate_keypair(&self, rng: impl CryptoRng) -> (EncapsulationKey, DecapsulationKey) {
983 with_params!(self, P, {
984 let (ek, dk) = <P as Kem>::generate_keypair(rng);
985 (
986 EncapsulationKey {
987 algorithm: *self,
988 value: ek.into_vec(),
989 },
990 DecapsulationKey {
991 algorithm: *self,
992 value: dk.into_vec(),
993 },
994 )
995 })
996 }
997
998 #[cfg(feature = "keygen")]
1003 pub fn generate_keypair_from_seed<B: AsRef<[u8]>>(
1004 &self,
1005 seed: B,
1006 ) -> McElieceResult<(EncapsulationKey, DecapsulationKey)> {
1007 with_params!(self, P, {
1008 let (ek, dk) = <P as Kem>::generate_keypair_from_seed(seed.as_ref())?;
1009 Ok((
1010 EncapsulationKey {
1011 algorithm: *self,
1012 value: ek.into_vec(),
1013 },
1014 DecapsulationKey {
1015 algorithm: *self,
1016 value: dk.into_vec(),
1017 },
1018 ))
1019 })
1020 }
1021
1022 #[cfg(feature = "encapsulate")]
1024 pub fn encapsulate(
1025 &self,
1026 key: &EncapsulationKey,
1027 rng: impl CryptoRng,
1028 ) -> McElieceResult<(Ciphertext, SharedSecret)> {
1029 if key.algorithm != *self {
1030 return Err(Error::AlgorithmMismatch);
1031 }
1032 with_params!(self, P, {
1033 if key.value.len() != P::PUBLIC_KEY_LENGTH {
1034 return Err(Error::InvalidEncapsulationKeyLength(key.value.len()));
1035 }
1036 let mut ct = vec![0u8; P::CIPHERTEXT_LENGTH];
1037 let mut ss = vec![0u8; P::SHARED_SECRET_LENGTH];
1038 if !hazmat::encap::encapsulate::<P>(&mut ct, &mut ss, &key.value, rng) {
1039 return Err(Error::EncapsulationKeyPadding);
1040 }
1041 Ok((
1042 Ciphertext {
1043 algorithm: *self,
1044 value: ct,
1045 },
1046 SharedSecret {
1047 algorithm: *self,
1048 value: ss,
1049 },
1050 ))
1051 })
1052 }
1053
1054 #[cfg(feature = "decapsulate")]
1061 pub fn decapsulate(
1062 &self,
1063 key: &DecapsulationKey,
1064 ciphertext: &Ciphertext,
1065 ) -> McElieceResult<SharedSecret> {
1066 if key.algorithm != *self || ciphertext.algorithm != *self {
1067 return Err(Error::AlgorithmMismatch);
1068 }
1069 with_params!(self, P, {
1070 if key.value.len() != P::SECRET_KEY_LENGTH {
1071 return Err(Error::InvalidDecapsulationKeyLength(key.value.len()));
1072 }
1073 if ciphertext.value.len() != P::CIPHERTEXT_LENGTH {
1074 return Err(Error::InvalidCiphertextLength(ciphertext.value.len()));
1075 }
1076 let mut ss = vec![0u8; P::SHARED_SECRET_LENGTH];
1077 if !hazmat::decap::decapsulate::<P>(&mut ss, &ciphertext.value, &key.value) {
1078 return Err(Error::CiphertextPadding);
1079 }
1080 Ok(SharedSecret {
1081 algorithm: *self,
1082 value: ss,
1083 })
1084 })
1085 }
1086
1087 #[cfg(feature = "keygen")]
1094 pub fn encapsulation_key_from_decapsulation_key(
1095 &self,
1096 key: &DecapsulationKey,
1097 ) -> McElieceResult<EncapsulationKey> {
1098 if key.algorithm != *self {
1099 return Err(Error::AlgorithmMismatch);
1100 }
1101 Ok(EncapsulationKey::from(key))
1102 }
1103
1104 pub fn encapsulation_key_from_bytes(&self, value: &[u8]) -> McElieceResult<EncapsulationKey> {
1106 with_params!(self, P, {
1107 hazmat::EncapsulationKey::<P>::from_slice(value).map(|key| EncapsulationKey {
1108 algorithm: *self,
1109 value: key.into_vec(),
1110 })
1111 })
1112 }
1113
1114 pub fn decapsulation_key_from_bytes(&self, value: &[u8]) -> McElieceResult<DecapsulationKey> {
1116 with_params!(self, P, {
1117 hazmat::DecapsulationKey::<P>::from_slice(value).map(|key| DecapsulationKey {
1118 algorithm: *self,
1119 value: key.into_vec(),
1120 })
1121 })
1122 }
1123
1124 pub fn ciphertext_from_bytes(&self, value: &[u8]) -> McElieceResult<Ciphertext> {
1126 with_params!(self, P, {
1127 hazmat::Ciphertext::<P>::from_slice(value).map(|ct| Ciphertext {
1128 algorithm: *self,
1129 value: ct.into_vec(),
1130 })
1131 })
1132 }
1133
1134 pub fn shared_secret_from_bytes(&self, value: &[u8]) -> McElieceResult<SharedSecret> {
1136 with_params!(self, P, {
1137 hazmat::SharedSecret::<P>::from_slice(value).map(|ss| SharedSecret {
1138 algorithm: *self,
1139 value: ss.into_vec(),
1140 })
1141 })
1142 }
1143}
1144
1145#[cfg(feature = "serde")]
1146impl serde::Serialize for Algorithm {
1147 fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
1148 where
1149 S: serde::Serializer,
1150 {
1151 if s.is_human_readable() {
1152 s.serialize_str(self.name())
1153 } else {
1154 s.serialize_u8(u8::from(*self))
1155 }
1156 }
1157}
1158
1159#[cfg(feature = "serde")]
1160impl<'de> serde::Deserialize<'de> for Algorithm {
1161 fn deserialize<D>(d: D) -> Result<Algorithm, D::Error>
1162 where
1163 D: serde::Deserializer<'de>,
1164 {
1165 if d.is_human_readable() {
1166 let name = <String as serde::Deserialize>::deserialize(d)?;
1167 name.parse().map_err(serde::de::Error::custom)
1168 } else {
1169 let tag = <u8 as serde::Deserialize>::deserialize(d)?;
1170 tag.try_into().map_err(serde::de::Error::custom)
1171 }
1172 }
1173}
1174
1175#[cfg(all(
1176 test,
1177 feature = "keygen",
1178 feature = "encapsulate",
1179 feature = "decapsulate"
1180))]
1181#[allow(clippy::unwrap_used)]
1182mod tests {
1183
1184 #[cfg(all(feature = "keygen", feature = "encapsulate", feature = "decapsulate"))]
1187 #[test]
1188 fn prepared_decapsulation_matches_the_plain_path() {
1189 use rand_core::{SeedableRng, UnwrapErr};
1190
1191 for &algorithm in Algorithm::enabled_algorithms() {
1192 let mut rng = UnwrapErr(rand_chacha::ChaCha8Rng::from_seed([29u8; 32]));
1193 let (ek, dk) = algorithm.generate_keypair(&mut rng);
1194 let prepared = dk.prepare();
1195 assert_eq!(prepared.algorithm(), algorithm);
1196 assert_eq!(prepared.key(), &dk);
1197
1198 let (ct, sent) = algorithm
1199 .encapsulate(&ek, &mut rng)
1200 .expect("a freshly generated key encapsulates");
1201 let direct = dk.decapsulate(&ct).expect("the ciphertext is well formed");
1202 let via_prepared = prepared.decapsulate(&ct).expect("likewise");
1203 assert_eq!(direct, sent, "{}", algorithm.name());
1204 assert_eq!(via_prepared, direct, "{} prepared", algorithm.name());
1205
1206 let mut damaged = ct.clone();
1209 damaged.value[0] ^= 1;
1210 let direct = dk.decapsulate(&damaged);
1211 let via_prepared = prepared.decapsulate(&damaged);
1212 assert_eq!(direct, via_prepared, "{} rejected", algorithm.name());
1213 if let Ok(secret) = direct {
1214 assert_ne!(secret, sent, "{} rejection", algorithm.name());
1215 }
1216
1217 let other = Algorithm::enabled_algorithms()
1219 .iter()
1220 .find(|&&a| a != algorithm)
1221 .copied();
1222 if let Some(other) = other {
1223 let (other_ek, _) = other.generate_keypair(&mut rng);
1224 let (other_ct, _) = other
1225 .encapsulate(&other_ek, &mut rng)
1226 .expect("a freshly generated key encapsulates");
1227 assert!(matches!(
1228 prepared.decapsulate(&other_ct),
1229 Err(Error::AlgorithmMismatch)
1230 ));
1231 }
1232 }
1233 }
1234 use super::*;
1235 use rand_core::SeedableRng;
1236
1237 #[test]
1238 fn every_algorithm_round_trips_through_its_public_conversions() {
1239 for &algorithm in Algorithm::enabled_algorithms() {
1240 let params = algorithm.params();
1241 assert_eq!(params.name, algorithm.name());
1242 assert_eq!(algorithm.to_string(), params.name);
1243 assert_eq!(params.name.parse::<Algorithm>().unwrap(), algorithm);
1244
1245 let id = u8::from(algorithm);
1246 assert_eq!(Algorithm::try_from(id).unwrap(), algorithm);
1247 assert_eq!(
1248 Algorithm::try_from(u16::from(algorithm)).unwrap(),
1249 algorithm
1250 );
1251 assert_eq!(
1252 Algorithm::try_from(u32::from(algorithm)).unwrap(),
1253 algorithm
1254 );
1255 assert_eq!(
1256 Algorithm::try_from(u64::from(algorithm)).unwrap(),
1257 algorithm
1258 );
1259 assert_eq!(
1260 Algorithm::try_from(usize::from(algorithm)).unwrap(),
1261 algorithm
1262 );
1263
1264 assert_eq!(params.k, params.n - params.m * params.t);
1265 assert_eq!(params.shared_secret_length, 32);
1266 assert_eq!(params.seed_length, 32);
1267 assert!(params.in_nist_submission || params.in_iso_standard);
1268 let syndrome_bytes = (params.m * params.t).div_ceil(8);
1270 assert_eq!(
1271 params.ciphertext_length,
1272 syndrome_bytes + if params.plaintext_confirmation { 32 } else { 0 }
1273 );
1274 }
1275
1276 assert!(Algorithm::try_from(0u8).is_err());
1277 assert!(Algorithm::try_from(200u8).is_err());
1278 assert!(Algorithm::try_from(300u16).is_err());
1279 assert!("not-an-algorithm".parse::<Algorithm>().is_err());
1280 }
1281
1282 #[test]
1283 fn the_standards_table_matches_the_published_lists() {
1284 for &algorithm in Algorithm::enabled_algorithms() {
1285 let params = algorithm.params();
1286 assert_eq!(params.in_iso_standard, params.n != 3488, "{}", params.name);
1288 assert_eq!(
1290 params.in_nist_submission, !params.plaintext_confirmation,
1291 "{}",
1292 params.name
1293 );
1294 }
1295 }
1296
1297 #[test]
1298 fn value_types_validate_lengths_and_hide_secrets() {
1299 for &algorithm in Algorithm::enabled_algorithms() {
1300 let params = algorithm.params();
1301
1302 let ek =
1303 EncapsulationKey::from_bytes(algorithm, vec![0; params.encapsulation_key_length])
1304 .unwrap();
1305 let dk =
1306 DecapsulationKey::from_bytes(algorithm, vec![0; params.decapsulation_key_length])
1307 .unwrap();
1308 let ct = Ciphertext::from_bytes(algorithm, vec![0; params.ciphertext_length]).unwrap();
1309 let ss =
1310 SharedSecret::from_bytes(algorithm, vec![0; params.shared_secret_length]).unwrap();
1311
1312 assert_eq!(ek.algorithm(), algorithm);
1313 assert_eq!(ek.value(), ek.as_ref());
1314 assert_eq!(dk.algorithm(), algorithm);
1315 assert_eq!(ct.algorithm(), algorithm);
1316 assert_eq!(ss.algorithm(), algorithm);
1317
1318 assert!(EncapsulationKey::from_bytes(algorithm, []).is_err());
1319 assert!(DecapsulationKey::from_bytes(algorithm, []).is_err());
1320 assert!(Ciphertext::from_bytes(algorithm, []).is_err());
1321 assert!(SharedSecret::from_bytes(algorithm, []).is_err());
1322
1323 assert!(!format!("{dk:?}").contains("value"));
1324 assert!(!format!("{ss:?}").contains("value"));
1325 assert!(format!("{ek:?}").contains("value"));
1326 }
1327 }
1328
1329 #[test]
1330 fn the_dynamic_api_rejects_mismatched_algorithms() {
1331 let alg = Algorithm::enabled_algorithms()[0];
1332 let Some(&other) = Algorithm::enabled_algorithms().iter().find(|&&a| a != alg) else {
1333 return;
1335 };
1336
1337 let mut rng = rand_chacha::ChaCha8Rng::from_seed([5u8; 32]);
1338 let (ek, dk) = alg.generate_keypair(&mut rng);
1339 let (ct, _) = alg.encapsulate(&ek, &mut rng).unwrap();
1340
1341 assert_eq!(
1342 other.encapsulate(&ek, &mut rng).unwrap_err(),
1343 Error::AlgorithmMismatch
1344 );
1345 assert_eq!(
1346 other.decapsulate(&dk, &ct).unwrap_err(),
1347 Error::AlgorithmMismatch
1348 );
1349
1350 let foreign_ct =
1351 Ciphertext::from_bytes(other, vec![0; other.params().ciphertext_length]).unwrap();
1352 assert_eq!(
1353 dk.decapsulate(&foreign_ct).unwrap_err(),
1354 Error::AlgorithmMismatch
1355 );
1356 }
1357
1358 #[test]
1359 fn the_dynamic_api_rejects_default_values_without_panicking() {
1360 let algorithm = Algorithm::default();
1365 let mut rng = rand_chacha::ChaCha8Rng::from_seed([6u8; 32]);
1366 let (ct, _ss) = algorithm
1367 .encapsulate(&EncapsulationKey::default(), &mut rng)
1368 .unwrap();
1369
1370 let key = DecapsulationKey::default();
1371 assert_eq!(key.seed(), [0u8; 32]);
1372 let plain = algorithm.decapsulate(&key, &ct).unwrap();
1373 let prepared = key.prepare();
1374 assert_eq!(prepared.decapsulate(&ct).unwrap(), plain);
1375 assert!(algorithm.decapsulate(&key, &Ciphertext::default()).is_ok());
1376
1377 let empty = Ciphertext {
1379 algorithm,
1380 value: Vec::new(),
1381 };
1382 assert_eq!(
1383 algorithm.decapsulate(&key, &empty).unwrap_err(),
1384 Error::InvalidCiphertextLength(0)
1385 );
1386 }
1387
1388 #[test]
1389 #[cfg(feature = "mceliece6960119f")]
1390 fn the_recommended_algorithm_is_an_enabled_mceliece6_set() {
1391 assert_eq!(Algorithm::RECOMMENDED, Algorithm::McEliece6960119f);
1392 assert!(Algorithm::enabled_algorithms().contains(&Algorithm::RECOMMENDED));
1393 }
1394
1395 #[test]
1396 #[cfg(all(
1397 feature = "keygen",
1398 feature = "mceliece348864",
1399 feature = "mceliece348864f"
1400 ))]
1401 fn public_key_recovery_rejects_a_key_from_a_sibling_parameter_set() {
1402 let algorithm = Algorithm::McEliece348864;
1406 let sibling = DecapsulationKey::from_bytes(
1407 Algorithm::McEliece348864f,
1408 vec![0; Algorithm::McEliece348864f.params().decapsulation_key_length],
1409 )
1410 .unwrap();
1411 assert_eq!(
1412 algorithm
1413 .encapsulation_key_from_decapsulation_key(&sibling)
1414 .unwrap_err(),
1415 Error::AlgorithmMismatch
1416 );
1417 }
1418
1419 #[test]
1420 fn a_round_trip_recovers_the_shared_secret_and_rejection_is_stable() {
1421 let alg = Algorithm::enabled_algorithms()[0];
1422 let mut rng = rand_chacha::ChaCha8Rng::from_seed([13u8; 32]);
1423 let (ek, dk) = alg.generate_keypair(&mut rng);
1424
1425 let (ct, sent) = ek.encapsulate(&mut rng).unwrap();
1426 assert_eq!(dk.decapsulate(&ct).unwrap(), sent);
1427 assert_eq!(EncapsulationKey::from(&dk), ek);
1428
1429 let mut tampered = ct.clone();
1430 tampered.value[0] ^= 1;
1431 let first = dk.decapsulate(&tampered).unwrap();
1432 let second = dk.decapsulate(&tampered).unwrap();
1433 assert_eq!(first, second);
1434 assert_ne!(first, sent);
1435 }
1436
1437 #[test]
1438 fn deterministic_generation_validates_the_seed_length() {
1439 for &algorithm in Algorithm::enabled_algorithms() {
1440 let seed = vec![0xA5; algorithm.params().seed_length];
1441 let first = algorithm.generate_keypair_from_seed(&seed).unwrap();
1442 let second = algorithm.generate_keypair_from_seed(&seed).unwrap();
1443 assert_eq!(first, second);
1444
1445 assert_eq!(
1446 algorithm
1447 .generate_keypair_from_seed(&seed[..seed.len() - 1])
1448 .unwrap_err(),
1449 Error::InvalidSeedLength(31)
1450 );
1451 let mut long = seed;
1452 long.push(0);
1453 assert_eq!(
1454 algorithm.generate_keypair_from_seed(long).unwrap_err(),
1455 Error::InvalidSeedLength(33)
1456 );
1457 }
1458 }
1459
1460 #[cfg(all(feature = "keygen", feature = "encapsulate"))]
1463 #[test]
1464 fn padding_accessors_report_both_outcomes() {
1465 for &algorithm in Algorithm::enabled_algorithms() {
1466 let mut rng = rand_chacha::ChaCha8Rng::from_seed([23u8; 32]);
1467 let (ek, _) = algorithm.generate_keypair(&mut rng);
1468 let (ct, _) = algorithm.encapsulate(&ek, &mut rng).unwrap();
1469
1470 assert!(ek.padding_is_zero(), "{} fresh key", algorithm.name());
1471 assert!(
1472 ct.padding_is_zero(),
1473 "{} fresh ciphertext",
1474 algorithm.name()
1475 );
1476
1477 let has_padding = algorithm.params().k % 8 != 0;
1479 let mut damaged = ek.clone();
1480 let last = damaged.value.len() - 1;
1481 damaged.value[last] = 0xFF;
1482 assert_eq!(
1483 damaged.padding_is_zero(),
1484 !has_padding,
1485 "{} damaged key",
1486 algorithm.name()
1487 );
1488
1489 let params = algorithm.params();
1492 let syndrome_bytes = (params.m * params.t).div_ceil(8);
1493 let ciphertext_has_padding = params.m * params.t % 8 != 0;
1494 let mut damaged = ct.clone();
1495 damaged.value[syndrome_bytes - 1] = 0xFF;
1496 assert_eq!(
1497 damaged.padding_is_zero(),
1498 !ciphertext_has_padding,
1499 "{} damaged ciphertext",
1500 algorithm.name()
1501 );
1502
1503 let mut truncated = ek;
1505 truncated.value.truncate(1);
1506 assert!(
1507 !truncated.padding_is_zero(),
1508 "{} short key",
1509 algorithm.name()
1510 );
1511 let mut truncated = ct;
1512 truncated.value.truncate(1);
1513 assert!(
1514 !truncated.padding_is_zero(),
1515 "{} short ciphertext",
1516 algorithm.name()
1517 );
1518 }
1519 }
1520
1521 #[cfg(feature = "serde")]
1522 mod serde_tests {
1523 use super::*;
1524
1525 #[cfg(all(feature = "keygen", feature = "encapsulate"))]
1528 #[test]
1529 fn deserialization_rejects_malformed_encodings() {
1530 let alg = Algorithm::enabled_algorithms()[0];
1531 let mut rng = rand_chacha::ChaCha8Rng::from_seed([17u8; 32]);
1532 let (ek, _) = alg.generate_keypair(&mut rng);
1533 let encoded = serde_json::to_string(&ek).unwrap();
1534
1535 let doubled_algorithm = encoded.replacen('{', r#"{"algorithm":"mceliece348864","#, 1);
1537 assert!(serde_json::from_str::<EncapsulationKey>(&doubled_algorithm).is_err());
1538 let doubled_value = encoded.replacen('{', r#"{"value":"00","#, 1);
1539 assert!(serde_json::from_str::<EncapsulationKey>(&doubled_value).is_err());
1540
1541 assert!(serde_json::from_str::<EncapsulationKey>(r#"{"value":"00"}"#).is_err());
1543 assert!(
1544 serde_json::from_str::<EncapsulationKey>(&encoded.replacen(
1545 '{',
1546 r#"{"nope":1,"#,
1547 1
1548 ))
1549 .is_err()
1550 );
1551 assert!(
1552 serde_json::from_str::<EncapsulationKey>(
1553 r#"{"algorithm":"mceliece348864","value":"zz"}"#
1554 )
1555 .is_err()
1556 );
1557
1558 assert!(serde_json::from_str::<EncapsulationKey>("[]").is_err());
1560 assert!(
1561 serde_json::from_str::<EncapsulationKey>(
1562 r#"{"algorithm":"mceliece348864","value":"00ff"}"#
1563 )
1564 .is_err()
1565 );
1566 }
1567
1568 macro_rules! serde_round_trip {
1569 ($name:ident, $ser:path, $de:path) => {
1570 #[test]
1571 fn $name() {
1572 let alg = Algorithm::enabled_algorithms()[0];
1573 let mut rng = rand_chacha::ChaCha8Rng::from_seed([3u8; 32]);
1574 let (ek, dk) = alg.generate_keypair(&mut rng);
1575 let (ct, ss) = alg.encapsulate(&ek, &mut rng).unwrap();
1576
1577 let encoded = $ser(&ek).unwrap();
1578 let decoded: EncapsulationKey = $de(&encoded).unwrap();
1579 assert_eq!(decoded, ek);
1580
1581 let encoded = $ser(&dk).unwrap();
1582 let decoded: DecapsulationKey = $de(&encoded).unwrap();
1583 assert_eq!(decoded, dk);
1584
1585 let encoded = $ser(&ct).unwrap();
1586 let decoded: Ciphertext = $de(&encoded).unwrap();
1587 assert_eq!(decoded, ct);
1588
1589 let encoded = $ser(&ss).unwrap();
1590 let decoded: SharedSecret = $de(&encoded).unwrap();
1591 assert_eq!(decoded, ss);
1592 }
1593 };
1594 }
1595
1596 serde_round_trip!(json, serde_json::to_string, serde_json::from_str);
1597 serde_round_trip!(toml, toml::to_string, toml::from_str);
1598 serde_round_trip!(yaml, yaml_serde::to_string, yaml_serde::from_str);
1599 serde_round_trip!(bare, serde_bare::to_vec, serde_bare::from_slice);
1600 serde_round_trip!(cbor, serde_cbor_2::to_vec, serde_cbor_2::from_slice);
1601 serde_round_trip!(postcard, postcard::to_stdvec, postcard::from_bytes);
1602 }
1603}