From b277f0d1e33be55f82c295efd89599a174ff360c Mon Sep 17 00:00:00 2001 From: Sean Bowe Date: Fri, 1 Jul 2016 22:10:30 -0600 Subject: [PATCH] Add DH key exchange example. --- examples/dh.rs | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 examples/dh.rs diff --git a/examples/dh.rs b/examples/dh.rs new file mode 100644 index 0000000..2e07f3c --- /dev/null +++ b/examples/dh.rs @@ -0,0 +1,34 @@ +// This is an example of three-party Diffie-Hellman key exchange +// Requires two rounds + +extern crate bn; +extern crate rand; + +use bn::*; + +fn main() { + let rng = &mut rand::thread_rng(); + + // Construct private keys + let alice_sk = Scalar::random(rng); + let bob_sk = Scalar::random(rng); + let carol_sk = Scalar::random(rng); + + // Construct public keys + let alice_pk = G1::one() * &alice_sk; + let bob_pk = G1::one() * &bob_sk; + let carol_pk = G1::one() * &carol_sk; + + // Round one: + let alice_dh_1 = &bob_pk * &carol_sk; + let bob_dh_1 = &carol_pk * &alice_sk; + let carol_dh_1 = &alice_pk * &bob_sk; + + // Round two: + let alice_dh_2 = alice_dh_1 * &alice_sk; + let bob_dh_2 = bob_dh_1 * &bob_sk; + let carol_dh_2 = carol_dh_1 * &carol_sk; + + // All parties should arrive to the same shared secret + assert!(alice_dh_2 == bob_dh_2 && bob_dh_2 == carol_dh_2); +}