p256/ecdh.rs
1//! Elliptic Curve Diffie-Hellman (Ephemeral) Support.
2//!
3//! This module contains a high-level interface for performing ephemeral
4//! Diffie-Hellman key exchanges using the secp256r1 elliptic curve.
5//!
6//! # Usage
7//!
8//! This usage example is from the perspective of two participants in the
9//! exchange, nicknamed "Alice" and "Bob".
10//!
11#![cfg_attr(all(feature = "ecdh", feature = "getrandom"), doc = "```")]
12#![cfg_attr(not(all(feature = "ecdh", feature = "getrandom")), doc = "```ignore")]
13//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
14//! // NOTE: requires the `ecdh` and `getrandom` crate features are enabled
15//! use p256::{
16//! Sec1Point, PublicKey,
17//! elliptic_curve::Generate,
18//! ecdh::EphemeralSecret
19//! };
20//!
21//! // Alice
22//! let alice_secret = EphemeralSecret::generate();
23//! let alice_pk_bytes = Sec1Point::from(alice_secret.public_key());
24//!
25//! // Bob
26//! let bob_secret = EphemeralSecret::generate();
27//! let bob_pk_bytes = Sec1Point::from(bob_secret.public_key());
28//!
29//! // Alice decodes Bob's serialized public key and computes a shared secret from it
30//! let bob_public = PublicKey::from_sec1_bytes(bob_pk_bytes.as_ref())?;
31//!
32//! let alice_shared = alice_secret.diffie_hellman(&bob_public);
33//!
34//! // Bob decodes Alice's serialized public key and computes the same shared secret
35//! let alice_public = PublicKey::from_sec1_bytes(alice_pk_bytes.as_ref())
36//! .expect("alice's public key is invalid!"); // In real usage, don't panic, handle this!
37//!
38//! let bob_shared = bob_secret.diffie_hellman(&alice_public);
39//!
40//! // Both participants arrive on the same shared secret
41//! assert_eq!(alice_shared.raw_secret_bytes(), bob_shared.raw_secret_bytes());
42//! # Ok(())
43//! # }
44//! ```
45
46pub use elliptic_curve::ecdh::diffie_hellman;
47
48use crate::NistP256;
49
50/// NIST P-256 Ephemeral Diffie-Hellman Secret.
51pub type EphemeralSecret = elliptic_curve::ecdh::EphemeralSecret<NistP256>;
52
53/// Shared secret value computed via ECDH key agreement.
54pub type SharedSecret = elliptic_curve::ecdh::SharedSecret<NistP256>;