dcrypt_api/traits/
kem.rs

1//! Trait definition for Key Encapsulation Mechanisms (KEM) with enhanced type safety
2//!
3//! This module provides a type-safe interface for key encapsulation mechanisms,
4//! which are used for secure key exchange in public-key cryptography.
5
6use crate::Result;
7use rand::{CryptoRng, RngCore};
8use zeroize::Zeroize;
9
10/// Trait for Key Encapsulation Mechanism (KEM) with domain-specific types
11pub trait Kem {
12    /// Public key type with appropriate constraints
13    type PublicKey: AsRef<[u8]> + AsMut<[u8]> + Clone;
14
15    /// Secret key type with security guarantees
16    type SecretKey: Zeroize + AsRef<[u8]> + AsMut<[u8]> + Clone;
17
18    /// Shared secret type with security guarantees
19    type SharedSecret: Zeroize + AsRef<[u8]> + AsMut<[u8]> + Clone;
20
21    /// Ciphertext type for the encapsulated key
22    type Ciphertext: AsRef<[u8]> + AsMut<[u8]> + Clone;
23
24    /// Keypair type for efficient storage of related keys
25    type KeyPair: Clone;
26
27    /// Returns the KEM algorithm name
28    fn name() -> &'static str;
29
30    /// Generate a new keypair
31    fn keypair<R: CryptoRng + RngCore>(rng: &mut R) -> Result<Self::KeyPair>;
32
33    /// Extract public key from keypair
34    fn public_key(keypair: &Self::KeyPair) -> Self::PublicKey;
35
36    /// Extract secret key from keypair
37    fn secret_key(keypair: &Self::KeyPair) -> Self::SecretKey;
38
39    /// Encapsulate a shared secret using the recipient's public key
40    fn encapsulate<R: CryptoRng + RngCore>(
41        rng: &mut R,
42        public_key: &Self::PublicKey,
43    ) -> Result<(Self::Ciphertext, Self::SharedSecret)>;
44
45    /// Decapsulate a shared secret using the private key
46    fn decapsulate(
47        secret_key: &Self::SecretKey,
48        ciphertext: &Self::Ciphertext,
49    ) -> Result<Self::SharedSecret>;
50}