ml_kem/
traits.rs

1//! Trait definitions
2
3use crate::{ArraySize, Ciphertext, Seed, SharedKey};
4use core::fmt::Debug;
5use hybrid_array::Array;
6use kem::{Decapsulate, Encapsulate};
7use rand_core::CryptoRng;
8
9#[cfg(feature = "deterministic")]
10use crate::B32;
11
12/// An object that knows what size it is
13pub trait EncodedSizeUser {
14    /// The size of an encoded object
15    type EncodedSize: ArraySize;
16
17    /// Parse an object from its encoded form
18    fn from_bytes(enc: &Encoded<Self>) -> Self;
19
20    /// Serialize an object to its encoded form
21    fn as_bytes(&self) -> Encoded<Self>;
22}
23
24/// A byte array encoding a value the indicated size
25pub type Encoded<T> = Array<u8, <T as EncodedSizeUser>::EncodedSize>;
26
27/// A value that can be encapsulated to.  Note that this interface is not safe: In order for the
28/// KEM to be secure, the `m` input must be randomly generated.
29#[cfg(feature = "deterministic")]
30pub trait EncapsulateDeterministic<EK, SS> {
31    /// Encapsulation error
32    type Error: Debug;
33
34    /// Encapsulates a fresh shared secret.
35    ///
36    /// # Errors
37    ///
38    /// Will vary depending on the underlying implementation.
39    fn encapsulate_deterministic(&self, m: &B32) -> Result<(EK, SS), Self::Error>;
40}
41
42/// A generic interface to a Key Encapsulation Method
43pub trait KemCore: Clone {
44    /// The size of a shared key generated by this KEM
45    type SharedKeySize: ArraySize;
46
47    /// The size of a ciphertext encapsulating a shared key
48    type CiphertextSize: ArraySize;
49
50    /// A decapsulation key for this KEM
51    type DecapsulationKey: Decapsulate<Ciphertext<Self>, SharedKey<Self>>
52        + EncodedSizeUser
53        + Debug
54        + PartialEq;
55
56    /// An encapsulation key for this KEM
57    type EncapsulationKey: Encapsulate<Ciphertext<Self>, SharedKey<Self>>
58        + EncodedSizeUser
59        + Clone
60        + Debug
61        + PartialEq;
62
63    /// Generate a new (decapsulation, encapsulation) key pair.
64    fn generate<R: CryptoRng + ?Sized>(
65        rng: &mut R,
66    ) -> (Self::DecapsulationKey, Self::EncapsulationKey);
67
68    /// Generate a new (decapsulation, encapsulation) key pair deterministically from the given
69    /// uniformly random seed value.
70    fn from_seed(seed: Seed) -> (Self::DecapsulationKey, Self::EncapsulationKey);
71}