Skip to content

Instantly share code, notes, and snippets.

@nixpulvis
Created March 16, 2020 03:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nixpulvis/0054ac41910bd436e4d5580761de3c4e to your computer and use it in GitHub Desktop.
Save nixpulvis/0054ac41910bd436e4d5580761de3c4e to your computer and use it in GitHub Desktop.
Diffe-Hellman-Merkle Key Exchange Demonstration (using curves crate)
//! ```cargo
//! [dependencies]
//! rand = "0.3.16"
//! curves = { git = "https://gitlab.com/neucrypt/curves", branch = "release" }
//! ```
extern crate rand;
extern crate curves;
use curves::{Secp, SecpOrd, ECGroup, Ford};
/// This demonstrates the math beneath a Diffe-Hellman-Merkle key exchange, and
/// is not meant to be meaningful in it of itself. Obviously A's and B's code
/// must be separated for this to accomplish anything.
fn key_exchange(g: Secp) -> (Secp, Secp)
{
// A random value generator, good enough for demonstration purposes.
let mut rng = rand::thread_rng();
// A's code.
let q1 = SecpOrd::rand(&mut rng);
let a = g.scalar(&q1);
// B's code.
let q2 = SecpOrd::rand(&mut rng);
let b = g.scalar(&q2);
// A's code, implying that B sent `b` to A.
let ka = b.scalar(&q1);
// B's code, implying that A sent `a` to B.
let kb = a.scalar(&q2);
// Return both party's normalized (affine?) keys.
(ka.affine(), kb.affine())
}
fn main() {
// Generate the generator.
let g = ECGroup::gen();
println!("Group generator is:\n {:?}\n\n", g);
let (ka, kb) = key_exchange(g);
assert_eq!(ka, kb);
println!("Successfully shared key:\n {:?}", ka);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment