Skip to main content

elliptic_curve/
ecdh.rs

1//! Elliptic Curve Diffie-Hellman Support.
2//!
3//! This module contains a generic ECDH implementation which is usable with
4//! any elliptic curve which implements the [`ProjectiveArithmetic`] trait (presently
5//! the `k256` and `p256` crates)
6//!
7//! # ECDH Ephemeral (ECDHE) Usage
8//!
9//! Ephemeral Diffie-Hellman provides a one-time key exchange between two peers
10//! using a randomly generated set of keys for each exchange.
11//!
12//! In practice ECDHE is used as part of an [Authenticated Key Exchange (AKE)][AKE]
13//! protocol (e.g. [SIGMA]), where an existing cryptographic trust relationship
14//! can be used to determine the authenticity of the ephemeral keys, such as
15//! a digital signature. Without such an additional step, ECDHE is insecure!
16//! (see security warning below)
17//!
18//! See the documentation for the [`EphemeralSecret`] type for more information
19//! on performing ECDH ephemeral key exchanges.
20//!
21//! # Static ECDH Usage
22//!
23//! Static ECDH key exchanges are supported via the low-level
24//! [`diffie_hellman`] function.
25//!
26//! [AKE]: https://en.wikipedia.org/wiki/Authenticated_Key_Exchange
27//! [SIGMA]: https://webee.technion.ac.il/~hugo/sigma-pdf.pdf
28
29use crate::{
30    weierstrass::Curve, AffinePoint, FieldBytes, NonZeroScalar, ProjectiveArithmetic,
31    ProjectivePoint, PublicKey, Scalar,
32};
33use core::borrow::Borrow;
34use group::Curve as _;
35use rand_core::{CryptoRng, RngCore};
36use zeroize::Zeroize;
37
38/// Low-level Elliptic Curve Diffie-Hellman (ECDH) function.
39///
40/// Whenever possible, we recommend using the high-level ECDH ephemeral API
41/// provided by [`EphemeralSecret`].
42///
43/// However, if you are implementing a protocol which requires a static scalar
44/// value as part of an ECDH exchange, this API can be used to compute a
45/// [`SharedSecret`] from that value.
46///
47/// Note that this API operates on the low-level [`NonZeroScalar`] and
48/// [`AffinePoint`] types. If you are attempting to use the higher-level
49/// [`SecretKey`][`crate::SecretKey`] and [`PublicKey`] types, you will
50/// need to use the following conversions:
51///
52/// ```ignore
53/// let shared_secret = elliptic_curve::ecdh::diffie_hellman(
54///     secret_key.secret_scalar(),
55///     public_key.as_affine()
56/// );
57/// ```
58pub fn diffie_hellman<C>(
59    secret_key: impl Borrow<NonZeroScalar<C>>,
60    public_key: impl Borrow<AffinePoint<C>>,
61) -> SharedSecret<C>
62where
63    C: Curve + ProjectiveArithmetic,
64    AffinePoint<C>: Zeroize,
65    Scalar<C>: Zeroize,
66    SharedSecret<C>: for<'a> From<&'a AffinePoint<C>>,
67{
68    let public_point = ProjectivePoint::<C>::from(*public_key.borrow());
69    let mut secret_point = (public_point * secret_key.borrow().as_ref()).to_affine();
70    let shared_secret = SharedSecret::from(&secret_point);
71    secret_point.zeroize();
72    shared_secret
73}
74
75/// Ephemeral Diffie-Hellman Secret.
76///
77/// These are ephemeral "secret key" values which are deliberately designed
78/// to avoid being persisted.
79///
80/// To perform an ephemeral Diffie-Hellman exchange, do the following:
81///
82/// - Have each participant generate an [`EphemeralSecret`] value
83/// - Compute the [`PublicKey`] for that value
84/// - Have each peer provide their [`PublicKey`] to their counterpart
85/// - Use [`EphemeralSecret`] and the other participant's [`PublicKey`]
86///   to compute a [`SharedSecret`] value.
87///
88/// # ⚠️ SECURITY WARNING ⚠️
89///
90/// Ephemeral Diffie-Hellman exchanges are unauthenticated and without a
91/// further authentication step are trivially vulnerable to man-in-the-middle
92/// attacks!
93///
94/// These exchanges should be performed in the context of a protocol which
95/// takes further steps to authenticate the peers in a key exchange.
96pub struct EphemeralSecret<C>
97where
98    C: Curve + ProjectiveArithmetic,
99    Scalar<C>: Zeroize,
100{
101    scalar: NonZeroScalar<C>,
102}
103
104impl<C> EphemeralSecret<C>
105where
106    C: Curve + ProjectiveArithmetic,
107    AffinePoint<C>: Zeroize,
108    Scalar<C>: Zeroize,
109    SharedSecret<C>: for<'a> From<&'a AffinePoint<C>>,
110{
111    /// Generate a cryptographically random [`EphemeralSecret`].
112    pub fn random(rng: impl CryptoRng + RngCore) -> Self {
113        Self {
114            scalar: NonZeroScalar::random(rng),
115        }
116    }
117
118    /// Get the public key associated with this ephemeral secret.
119    ///
120    /// The `compress` flag enables point compression.
121    pub fn public_key(&self) -> PublicKey<C> {
122        PublicKey::from_secret_scalar(&self.scalar)
123    }
124
125    /// Compute a Diffie-Hellman shared secret from an ephemeral secret and the
126    /// public key of the other participant in the exchange.
127    pub fn diffie_hellman(&self, public_key: &PublicKey<C>) -> SharedSecret<C> {
128        diffie_hellman(&self.scalar, public_key.as_affine())
129    }
130}
131
132impl<C> From<&EphemeralSecret<C>> for PublicKey<C>
133where
134    C: Curve + ProjectiveArithmetic,
135    AffinePoint<C>: Zeroize,
136    Scalar<C>: Zeroize,
137    SharedSecret<C>: for<'a> From<&'a AffinePoint<C>>,
138{
139    fn from(ephemeral_secret: &EphemeralSecret<C>) -> Self {
140        ephemeral_secret.public_key()
141    }
142}
143
144impl<C> Zeroize for EphemeralSecret<C>
145where
146    C: Curve + ProjectiveArithmetic,
147    Scalar<C>: Zeroize,
148{
149    fn zeroize(&mut self) {
150        self.scalar.zeroize()
151    }
152}
153
154impl<C> Drop for EphemeralSecret<C>
155where
156    C: Curve + ProjectiveArithmetic,
157    Scalar<C>: Zeroize,
158{
159    fn drop(&mut self) {
160        self.zeroize();
161    }
162}
163
164/// Shared secret value computed via ECDH key agreement.
165///
166/// This value contains the raw serialized x-coordinate of the elliptic curve
167/// point computed from a Diffie-Hellman exchange.
168///
169/// # ⚠️ WARNING: NOT UNIFORMLY RANDOM! ⚠️
170///
171/// This value is not uniformly random and should not be used directly
172/// as a cryptographic key for anything which requires that property
173/// (e.g. symmetric ciphers).
174///
175/// Instead, the resulting value should be used as input to a Key Derivation
176/// Function (KDF) or cryptographic hash function to produce a symmetric key.
177// TODO(tarcieri): KDF traits and support for deriving uniform keys
178// See: https://github.com/RustCrypto/traits/issues/5
179pub struct SharedSecret<C: Curve> {
180    /// Computed secret value
181    secret_bytes: FieldBytes<C>,
182}
183
184impl<C: Curve> SharedSecret<C> {
185    /// Shared secret value, serialized as bytes.
186    ///
187    /// As noted in the comments for this struct, this value is non-uniform and
188    /// should not be used directly as a symmetric encryption key, but instead
189    /// as input to a KDF (or failing that, a hash function) used to produce
190    /// a symmetric key.
191    pub fn as_bytes(&self) -> &FieldBytes<C> {
192        &self.secret_bytes
193    }
194}
195
196impl<C: Curve> From<FieldBytes<C>> for SharedSecret<C> {
197    /// NOTE: this impl is intended to be used by curve implementations to
198    /// instantiate a [`SharedSecret`] value from their respective
199    /// [`AffinePoint`] type.
200    ///
201    /// Curve implementations should provide the field element representing
202    /// the affine x-coordinate as `secret_bytes`.
203    fn from(secret_bytes: FieldBytes<C>) -> Self {
204        Self { secret_bytes }
205    }
206}
207
208impl<C: Curve> Zeroize for SharedSecret<C> {
209    fn zeroize(&mut self) {
210        self.secret_bytes.zeroize()
211    }
212}
213
214impl<C: Curve> Drop for SharedSecret<C> {
215    fn drop(&mut self) {
216        self.zeroize();
217    }
218}