Skip to main content

miden_crypto/ecdh/
x25519.rs

1//! X25519 (Elliptic Curve Diffie-Hellman) key agreement implementation using
2//! Curve25519.
3//!
4//! Note that the intended use is in the context of a one-way, sender initiated key agreement
5//! scenario. Namely, when the sender knows the (static) public key of the receiver and it
6//! uses that, together with an ephemeral secret key that it generates, to derive a shared
7//! secret.
8//!
9//! This shared secret will then be used to encrypt some message (using for example a key
10//! derivation function).
11//!
12//! The public key associated with the ephemeral secret key will be sent alongside the encrypted
13//! message.
14
15use alloc::vec::Vec;
16
17use hkdf::Hkdf;
18use rand::CryptoRng;
19use sha2::Sha256;
20use subtle::ConstantTimeEq;
21
22use crate::{
23    dsa::eddsa_25519_sha512::{KeyExchangeKey, PublicKey},
24    ecdh::KeyAgreementScheme,
25    utils::{
26        ByteReader, ByteWriter, Deserializable, DeserializationError, Serializable,
27        zeroize::{Zeroize, ZeroizeOnDrop},
28    },
29};
30// SHARED SECRETE
31// ================================================================================================
32
33/// A shared secret computed using the X25519 (Elliptic Curve Diffie-Hellman) key agreement.
34///
35/// This type implements `ZeroizeOnDrop` because the inner `x25519_dalek::SharedSecret`
36/// implements it, ensuring the shared secret is securely wiped from memory when dropped.
37pub struct SharedSecret {
38    bytes: [u8; 32],
39}
40impl SharedSecret {
41    pub(crate) fn new(inner: x25519_dalek::SharedSecret) -> SharedSecret {
42        Self { bytes: inner.to_bytes() }
43    }
44
45    /// Returns a HKDF that can be used to derive uniform keys from the shared secret.
46    pub fn extract(&self, salt: Option<&[u8]>) -> Hkdf<Sha256> {
47        Hkdf::new(salt, &self.bytes)
48    }
49}
50
51impl Zeroize for SharedSecret {
52    fn zeroize(&mut self) {
53        self.bytes.zeroize();
54    }
55}
56
57impl Drop for SharedSecret {
58    fn drop(&mut self) {
59        self.zeroize();
60    }
61}
62
63impl ZeroizeOnDrop for SharedSecret {}
64
65impl AsRef<[u8]> for SharedSecret {
66    fn as_ref(&self) -> &[u8] {
67        &self.bytes
68    }
69}
70
71// EPHEMERAL SECRET KEY
72// ================================================================================================
73
74/// Ephemeral secret key for X25519 key agreement.
75///
76/// This type implements `ZeroizeOnDrop` because the inner `x25519_dalek::EphemeralSecret`
77/// implements it, ensuring the secret key material is securely wiped from memory when dropped.
78pub struct EphemeralSecretKey {
79    inner: x25519_dalek::EphemeralSecret,
80}
81
82impl ZeroizeOnDrop for EphemeralSecretKey {}
83
84impl EphemeralSecretKey {
85    /// Generates a new random ephemeral secret key using the OS random number generator.
86    #[cfg(feature = "std")]
87    #[allow(clippy::new_without_default)]
88    pub fn new() -> Self {
89        let mut rng = rand::rng();
90
91        Self::with_rng(&mut rng)
92    }
93
94    /// Generates a new random ephemeral secret key using the provided RNG.
95    pub fn with_rng<R: CryptoRng>(rng: &mut R) -> Self {
96        let sk = x25519_dalek::EphemeralSecret::random_from_rng(rng);
97        Self { inner: sk }
98    }
99
100    /// Returns the corresponding ephemeral public key.
101    pub fn public_key(&self) -> EphemeralPublicKey {
102        EphemeralPublicKey {
103            inner: x25519_dalek::PublicKey::from(&self.inner),
104        }
105    }
106
107    /// Computes a Diffie-Hellman shared secret from this ephemeral secret key and the other party's
108    /// static public key.
109    pub fn diffie_hellman(self, pk_other: &PublicKey) -> SharedSecret {
110        let shared = self.inner.diffie_hellman(&pk_other.to_x25519());
111        SharedSecret::new(shared)
112    }
113}
114
115// EPHEMERAL PUBLIC KEY
116// ================================================================================================
117
118/// Ephemeral public key for X25519 agreement.
119#[derive(Debug, Clone, PartialEq, Eq)]
120#[cfg_attr(
121    all(feature = "arbitrary", test),
122    miden_test_serialization_macros::serialization_test
123)]
124pub struct EphemeralPublicKey {
125    pub(crate) inner: x25519_dalek::PublicKey,
126}
127
128#[cfg(any(test, feature = "arbitrary"))]
129mod ephemeral_key_arbitrary {
130    use proptest::prelude::*;
131    use rand_chacha::{ChaCha20Rng, rand_core::SeedableRng};
132
133    use super::EphemeralPublicKey;
134    use crate::ecdh::x25519::EphemeralSecretKey;
135
136    impl Arbitrary for EphemeralPublicKey {
137        type Parameters = ();
138        type Strategy = BoxedStrategy<Self>;
139
140        fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy {
141            // The reader rejects twist and small-order points; derive the public key from a
142            // deterministically seeded ephemeral secret - valid by construction.
143            any::<[u8; 32]>()
144                .prop_map(|seed| {
145                    let mut rng = ChaCha20Rng::from_seed(seed);
146                    EphemeralSecretKey::with_rng(&mut rng).public_key()
147                })
148                .boxed()
149        }
150    }
151}
152
153impl Serializable for EphemeralPublicKey {
154    fn write_into<W: ByteWriter>(&self, target: &mut W) {
155        target.write_bytes(self.inner.as_bytes());
156    }
157}
158
159impl Deserializable for EphemeralPublicKey {
160    fn read_from<R: ByteReader>(source: &mut R) -> Result<Self, DeserializationError> {
161        let bytes: [u8; 32] = source.read_array()?;
162        // Reject twist points and low-order points. We intentionally avoid the more expensive
163        // torsion-free check; small-order rejection mitigates the most dangerous malleability
164        // issues, even though it does not guarantee torsion-freeness.
165        let mont = curve25519_dalek::montgomery::MontgomeryPoint(bytes);
166        let edwards = mont.to_edwards(0).ok_or_else(|| {
167            DeserializationError::InvalidValue("Invalid X25519 public key".into())
168        })?;
169        if edwards.is_small_order() {
170            return Err(DeserializationError::InvalidValue("Invalid X25519 public key".into()));
171        }
172
173        Ok(Self {
174            inner: x25519_dalek::PublicKey::from(bytes),
175        })
176    }
177}
178
179// KEY AGREEMENT TRAIT IMPLEMENTATION
180// ================================================================================================
181
182pub struct X25519;
183
184impl KeyAgreementScheme for X25519 {
185    type EphemeralSecretKey = EphemeralSecretKey;
186    type EphemeralPublicKey = EphemeralPublicKey;
187
188    type SecretKey = KeyExchangeKey;
189    type PublicKey = PublicKey;
190
191    type SharedSecret = SharedSecret;
192
193    fn public_key(static_sk: &Self::SecretKey) -> Self::PublicKey {
194        static_sk.public_key()
195    }
196
197    fn generate_ephemeral_keypair<R: CryptoRng>(
198        rng: &mut R,
199    ) -> (Self::EphemeralSecretKey, Self::EphemeralPublicKey) {
200        let sk = EphemeralSecretKey::with_rng(rng);
201        let pk = sk.public_key();
202
203        (sk, pk)
204    }
205
206    fn exchange_ephemeral_static(
207        ephemeral_sk: Self::EphemeralSecretKey,
208        static_pk: &Self::PublicKey,
209    ) -> Result<Self::SharedSecret, super::KeyAgreementError> {
210        let shared = ephemeral_sk.diffie_hellman(static_pk);
211        if is_all_zero(shared.as_ref()) {
212            return Err(super::KeyAgreementError::InvalidSharedSecret);
213        }
214        Ok(shared)
215    }
216
217    fn exchange_static_ephemeral(
218        static_sk: &Self::SecretKey,
219        ephemeral_pk: &Self::EphemeralPublicKey,
220    ) -> Result<Self::SharedSecret, super::KeyAgreementError> {
221        let shared = static_sk.get_shared_secret(ephemeral_pk.clone());
222        if is_all_zero(shared.as_ref()) {
223            return Err(super::KeyAgreementError::InvalidSharedSecret);
224        }
225        Ok(shared)
226    }
227
228    fn extract_key_material(
229        shared_secret: &Self::SharedSecret,
230        length: usize,
231        info: &[u8],
232    ) -> Result<Vec<u8>, super::KeyAgreementError> {
233        super::extract_key_material(shared_secret.as_ref(), None, length, info)
234    }
235}
236
237fn is_all_zero(bytes: &[u8]) -> bool {
238    // Empty input is treated as invalid caller input rather than "all zero".
239    if bytes.is_empty() {
240        return false;
241    }
242    let acc = bytes.iter().fold(0u8, |acc, &byte| acc | byte);
243    acc.ct_eq(&0u8).into()
244}
245
246// TESTS
247// ================================================================================================
248
249#[cfg(test)]
250mod tests {
251    use curve25519_dalek::{constants::EIGHT_TORSION, montgomery::MontgomeryPoint};
252
253    use super::*;
254    use crate::{
255        dsa::eddsa_25519_sha512::KeyExchangeKey, ecdh::KeyAgreementError,
256        rand::test_utils::seeded_rng, utils::Deserializable,
257    };
258
259    #[test]
260    fn key_agreement() {
261        let mut rng = seeded_rng([0u8; 32]);
262
263        // 1. Generate the static key-pair for Alice
264        let sk = KeyExchangeKey::with_rng(&mut rng);
265        let pk = sk.public_key();
266
267        // 2. Generate the ephemeral key-pair for Bob
268        let sk_e = EphemeralSecretKey::with_rng(&mut rng);
269        let pk_e = sk_e.public_key();
270
271        // 3. Bob computes the shared secret key (Bob will send pk_e with the encrypted note to
272        //    Alice)
273        let shared_secret_key_1 = sk_e.diffie_hellman(&pk);
274
275        // 4. Alice uses its secret key and the ephemeral public key sent with the encrypted note by
276        //    Bob in order to create the shared secret key. This shared secret key will be used to
277        //    decrypt the encrypted note
278        let shared_secret_key_2 = sk.get_shared_secret(pk_e);
279
280        // Check that the computed shared secret keys are equal
281        assert_eq!(shared_secret_key_1.as_ref(), shared_secret_key_2.as_ref());
282    }
283
284    #[test]
285    fn ephemeral_public_key_rejects_small_order() {
286        let bytes = EIGHT_TORSION[1].to_montgomery().to_bytes();
287        let result = EphemeralPublicKey::read_from_bytes(&bytes);
288        assert!(result.is_err());
289    }
290
291    #[test]
292    fn ephemeral_public_key_rejects_twist_point() {
293        let bytes = find_twist_point_bytes();
294        let result = EphemeralPublicKey::read_from_bytes(&bytes);
295        assert!(result.is_err());
296    }
297
298    #[test]
299    fn exchange_static_ephemeral_rejects_zero_shared_secret() {
300        let mut rng = seeded_rng([0u8; 32]);
301        let static_sk = KeyExchangeKey::with_rng(&mut rng);
302
303        let low_order_bytes = EIGHT_TORSION[0].to_montgomery().to_bytes();
304        let low_order_pk = EphemeralPublicKey {
305            inner: x25519_dalek::PublicKey::from(low_order_bytes),
306        };
307
308        let result = X25519::exchange_static_ephemeral(&static_sk, &low_order_pk);
309        assert!(matches!(result, Err(KeyAgreementError::InvalidSharedSecret)));
310    }
311
312    #[test]
313    fn is_all_zero_accepts_arbitrary_lengths() {
314        assert!(!is_all_zero(&[]));
315        assert!(is_all_zero(&[0u8; 16]));
316        assert!(!is_all_zero(&[0u8, 1u8, 0u8, 0u8]));
317    }
318
319    fn find_twist_point_bytes() -> [u8; 32] {
320        let mut bytes = [0u8; 32];
321        for i in 0u16..=u16::MAX {
322            bytes[0] = (i & 0xff) as u8;
323            bytes[1] = (i >> 8) as u8;
324            if MontgomeryPoint(bytes).to_edwards(0).is_none() {
325                return bytes;
326            }
327        }
328        panic!("no twist point found in 16-bit search space");
329    }
330}