askar_crypto/kdf/
mod.rs

1//! Key derivation function traits and implementations
2
3#[cfg(feature = "alloc")]
4use crate::buffer::SecretBytes;
5use crate::{buffer::WriteBuffer, error::Error};
6
7#[cfg(feature = "argon2")]
8#[cfg_attr(docsrs, doc(cfg(feature = "argon2")))]
9pub mod argon2;
10
11pub mod concat;
12
13pub mod ecdh_1pu;
14
15pub mod ecdh_es;
16
17/// Trait for keys supporting Diffie-Helman key exchange
18pub trait KeyExchange<Rhs: ?Sized = Self> {
19    /// Perform a key exchange, writing the result to the provided buffer.
20    fn write_key_exchange(&self, other: &Rhs, out: &mut dyn WriteBuffer) -> Result<(), Error>;
21
22    #[cfg(feature = "alloc")]
23    #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
24    /// Perform a key exchange and return a new allocated buffer.
25    fn key_exchange_bytes(&self, other: &Rhs) -> Result<SecretBytes, Error> {
26        let mut buf = SecretBytes::with_capacity(128);
27        self.write_key_exchange(other, &mut buf)?;
28        Ok(buf)
29    }
30}
31
32/// Trait for instantiation from a key exchange
33pub trait FromKeyExchange<Lhs: ?Sized, Rhs: ?Sized>: Sized {
34    /// Derive an instance of this key directly from a supported key exchange
35    fn from_key_exchange(lhs: &Lhs, rhs: &Rhs) -> Result<Self, Error>;
36}
37
38/// Trait implemented by key derivation methods
39pub trait KeyDerivation {
40    /// Derive the raw bytes of a key from this KDF
41    fn derive_key_bytes(&mut self, key_output: &mut [u8]) -> Result<(), Error>;
42}
43
44/// Trait for instantiation from a key derivation
45pub trait FromKeyDerivation {
46    /// Create a new instance of a key from a key derivation
47    fn from_key_derivation<D: KeyDerivation>(derive: D) -> Result<Self, Error>
48    where
49        Self: Sized;
50}