ssb_crypto/
ephemeral.rs

1//! Ephemeral (curve25519) keys and operations for deriving shared secrets via
2//! [Elliptic-curve Diffie–Hellman](https://en.wikipedia.org/wiki/Elliptic-curve_Diffie–Hellman)
3use core::mem::size_of;
4use zerocopy::{AsBytes, FromBytes};
5use zeroize::Zeroize;
6
7// pub use box_::{PublicKey as EphPublicKey, SecretKey as EphSecretKey};
8
9#[cfg(all(feature = "dalek", not(feature = "force_sodium")))]
10use crate::dalek::ephemeral as eph;
11#[cfg(all(
12    feature = "sodium",
13    any(feature = "force_sodium", not(feature = "dalek"))
14))]
15use crate::sodium::ephemeral as eph;
16
17#[cfg(any(feature = "sodium", feature = "dalek"))]
18pub use eph::{
19    derive_shared_secret, derive_shared_secret_pk, derive_shared_secret_sk, sk_to_curve,
20};
21
22#[cfg(any(feature = "sodium", all(feature = "dalek", feature = "getrandom")))]
23pub use eph::generate_ephemeral_keypair;
24
25#[cfg(feature = "dalek")]
26pub use crate::dalek::ephemeral::generate_ephemeral_keypair_with_rng;
27
28/// The secret half of an ephemeral key pair; used for deriving a short-term shared secret for
29/// secure communication.
30#[derive(Zeroize)]
31#[zeroize(drop)]
32pub struct EphSecretKey(pub [u8; 32]);
33impl EphSecretKey {
34    /// The size of an EphSecretKey, in bytes (32).
35    pub const SIZE: usize = size_of::<Self>();
36}
37
38/// The public half of an ephemeral key pair.
39#[derive(Copy, Clone, AsBytes, FromBytes)]
40#[repr(C)]
41pub struct EphPublicKey(pub [u8; 32]);
42impl EphPublicKey {
43    /// The size of an EphPublicKey, in bytes (32).
44    pub const SIZE: usize = size_of::<Self>();
45
46    /// Deserialize from a byte slice.
47    ///
48    /// The slice must have length 32.
49    pub fn from_slice(s: &[u8]) -> Option<Self> {
50        if s.len() == Self::SIZE {
51            let mut out = Self([0; Self::SIZE]);
52            out.0.copy_from_slice(s);
53            Some(out)
54        } else {
55            None
56        }
57    }
58}
59
60/// A secret that's shared by two participants in a secure communication,
61/// derived from their respective key pairs.
62#[derive(AsBytes, Clone, Zeroize)]
63#[repr(C)]
64#[zeroize(drop)]
65pub struct SharedSecret(pub [u8; 32]);