With ECDH (Elliptic Curve Diffie Hellman) we can generate a shared key. Alice generates a secret value (\(a\)) and Bob generates his secret value (\(b\)). Next Alice sends a public value of \(aG\) and Bob sends \(bG\), and where \(G\) is the base point on the curve. Alice then creates \(a(bG)\) and Bob will create \(b(aG)\), and which should be the same value. The curve used is \(y^2 = x^3+7\) and the prime number is \(p = 2^{256} - 2^{32} - 977\).
ECDH in Rust using secp256k1 |
Code
First we create the project with:
cargo new ecdh
We then go into the ecdsa folder, and add the following to the cargo.toml file:
[package] name = "ecdh" version = "1.0.0" authors = ["Bill"] [dependencies] k256={version = "0.9.6", features = ["ecdh"]} hex="0.4.3" rand_core="0.6.3"
Notice that to use the ECDH feature, we need to enable this in the toml file. For this we will use P256 for the key exchange:
use k256::{EncodedPoint, PublicKey, ecdh::EphemeralSecret}; use rand_core::OsRng; fn main() { let a = EphemeralSecret::random(&mut OsRng); let A = EncodedPoint::from(a.public_key()); let b = EphemeralSecret::random(&mut OsRng); let B = EncodedPoint::from(b.public_key()); let bob_public = PublicKey::from_sec1_bytes(B.as_ref()).expect("Bob's public key invalid"); let alice_public = PublicKey::from_sec1_bytes(A.as_ref()).expect("Alice's public key invalid"); let Abytes= A.as_ref(); println!("\nAlice public key {:x?}",hex::encode(Abytes)); let Bbytes= B.as_ref(); println!("\nBob public key {:x?}",hex::encode(Bbytes)); let alice_shared = a.diffie_hellman(&bob_public); let bob_shared = b.diffie_hellman(&alice_public); let shared1= alice_shared.as_bytes(); println!("\nAlice shared key {:x?}",hex::encode(shared1)); let shared2= bob_shared.as_bytes(); println!("\nBob shared key {:x?}",hex::encode(shared2)); if (alice_shared.as_bytes()==bob_shared.as_bytes()){ println!("\nKeys are the same") } }
Finally we simply build with:
cargo build
A sample run is:
Alice public key "02bc1fa061a5c713e59694ba3e07b6c5d1f12bd0bafc2d9f54c2f49520ebb81c66" Bob public key "037abff3b72b07b74cb2f7bb824312a870659f27eb638f9e3efc2bacd2cca9eabb" Alice shared key "a3ed90d16b686eda104527b94a19b0343ebb0cb5df77b6ef361c12e95e0f3dc2" Bob shared key "a3ed90d16b686eda104527b94a19b0343ebb0cb5df77b6ef361c12e95e0f3dc2" Keys are the same