Skip to main content

oxicrypto_core/traits/
kex.rs

1use alloc::vec::Vec;
2
3use crate::CryptoError;
4
5/// Diffie-Hellman or similar key-agreement primitive.
6pub trait KeyAgreement: Send + Sync {
7    /// Human-readable algorithm identifier (e.g. `"X25519"`).
8    #[must_use]
9    fn name(&self) -> &'static str;
10    /// Length of the scalar (private key) in bytes.
11    #[must_use]
12    fn scalar_len(&self) -> usize;
13    /// Length of the public point in bytes.
14    #[must_use]
15    fn point_len(&self) -> usize;
16    /// Length of the shared secret in bytes.
17    ///
18    /// Defaults to `self.scalar_len()`, which is correct for all current
19    /// implementations (X25519: 32, ECDH P-256: 32, P-384: 48, P-521: 66,
20    /// X448: 56).
21    #[must_use]
22    fn shared_secret_len(&self) -> usize {
23        self.scalar_len()
24    }
25    /// Perform ECDH and write the shared secret into `shared_out`.
26    #[must_use = "result must be checked"]
27    fn agree(
28        &self,
29        my_secret: &[u8],
30        their_public: &[u8],
31        shared_out: &mut [u8],
32    ) -> Result<(), CryptoError>;
33    /// Convenience: perform ECDH and return the shared secret as a [`Vec<u8>`].
34    ///
35    /// The output length equals [`shared_secret_len`](KeyAgreement::shared_secret_len).
36    #[must_use = "result must be checked"]
37    fn agree_to_vec(&self, my_secret: &[u8], their_public: &[u8]) -> Result<Vec<u8>, CryptoError> {
38        let mut out = alloc::vec![0u8; self.shared_secret_len()];
39        self.agree(my_secret, their_public, &mut out)?;
40        Ok(out)
41    }
42}