Skip to main content

dcrypt_kem/
lib.rs

1//! Key Encapsulation Mechanisms (KEM) and Key Exchange
2//!
3//! This crate implements various key encapsulation mechanisms and key exchange
4//! protocols, both traditional and post-quantum.
5
6#![cfg_attr(not(feature = "std"), no_std)]
7#![forbid(unsafe_code)]
8
9extern crate alloc;
10
11#[cfg(feature = "traditional")]
12macro_rules! impl_zeroize_tuple {
13    ($type:ty) => {
14        impl dcrypt_internal::zeroing::Zeroize for $type {
15            fn zeroize(&mut self) {
16                dcrypt_internal::zeroing::Zeroize::zeroize(&mut self.0);
17            }
18        }
19    };
20}
21
22#[cfg(feature = "traditional")]
23macro_rules! impl_zeroize_on_drop_tuple {
24    ($type:ty) => {
25        impl_zeroize_tuple!($type);
26
27        impl Drop for $type {
28            fn drop(&mut self) {
29                dcrypt_internal::zeroing::Zeroize::zeroize(self);
30            }
31        }
32
33        impl dcrypt_internal::zeroing::ZeroizeOnDrop for $type {}
34    };
35}
36
37#[cfg(test)]
38pub(crate) mod test_rng {
39    use core::sync::atomic::{AtomicU64, Ordering};
40    use dcrypt_internal::random::{
41        try_fill_bytes_zeroing_on_error, ChaCha20Rng, CryptoRng, Error, RngCore,
42    };
43
44    static NEXT_STREAM: AtomicU64 = AtomicU64::new(1);
45
46    pub struct TestRng;
47
48    impl RngCore for TestRng {
49        fn try_fill_bytes(&mut self, destination: &mut [u8]) -> Result<(), Error> {
50            let stream = NEXT_STREAM.fetch_add(1, Ordering::Relaxed);
51            let mut seed = [0u8; 32];
52            seed[..8].copy_from_slice(&stream.to_le_bytes());
53            let mut rng = ChaCha20Rng::from_seed(seed);
54            try_fill_bytes_zeroing_on_error(&mut rng, destination)
55        }
56    }
57
58    impl CryptoRng for TestRng {}
59}
60
61#[cfg(feature = "traditional")]
62pub mod ecdh;
63pub mod error;
64#[cfg(feature = "post-quantum")]
65pub mod ml_kem;
66
67// Re-exports
68#[cfg(feature = "traditional")]
69pub use ecdh::{EcdhK256, EcdhP224, EcdhP256, EcdhP384, EcdhP521};
70#[cfg(feature = "post-quantum")]
71pub use ml_kem::{
72    MlKem, MlKem1024, MlKem1024Ciphertext, MlKem1024DecapsulationKey, MlKem1024EncapsulationKey,
73    MlKem1024KeyPair, MlKem1024Params, MlKem512, MlKem512Ciphertext, MlKem512DecapsulationKey,
74    MlKem512EncapsulationKey, MlKem512KeyPair, MlKem512Params, MlKem768, MlKem768Ciphertext,
75    MlKem768DecapsulationKey, MlKem768EncapsulationKey, MlKem768KeyPair, MlKem768Params,
76    MlKemCiphertext, MlKemDecapsulationKey, MlKemEncapsulationKey, MlKemKeyPair, MlKemParameterSet,
77    MlKemSharedSecret, ML_KEM_SHARED_SECRET_BYTES,
78};