Published at Feb 10 2019
·
1 comment

Instructions

Test suite

Solution

Diffie-Hellman key exchange.

Alice and Bob use Diffie-Hellman key exchange to share secrets. They start with prime numbers, pick private keys, generate and share public keys, and then generate a shared secret key.

The test program supplies prime numbers p and g.

Alice picks a private key, a, greater than 1 and less than p. Bob does the same to pick a private key b.

Alice calculates a public key A.

```
A = g**a mod p
```

Using the same p and g, Bob similarly calculates a public key B from his private key b.

Alice and Bob exchange public keys. Alice calculates secret key s.

```
s = B**a mod p
```

Bob calculates

```
s = A**b mod p
```

The calculations produce the same result! Alice and Bob now share secret s.

One possible solution for this exercise is to implement your own modular exponentiation function. To learn more about it refer to the following page.

Refer to the exercism help page for Rust installation and learning resources.

Execute the tests with:

```
$ cargo test
```

All but the first test have been ignored. After you get the first test to
pass, open the tests source file which is located in the `tests`

directory
and remove the `#[ignore]`

flag from the next test and get the tests to pass
again. Each separate test is a function with `#[test]`

flag above it.
Continue, until you pass every test.

If you wish to run all tests without editing the tests source file, use:

```
$ cargo test -- --ignored
```

To run a specific test, for example `some_test`

, you can use:

```
$ cargo test some_test
```

If the specific test is ignored use:

```
$ cargo test some_test -- --ignored
```

To learn more about Rust tests refer to the online test documentation

Make sure to read the Modules chapter if you haven't already, it will help you with organizing your files.

The exercism/rust repository on GitHub is the home for all of the Rust exercises. If you have feedback about an exercise, or want to help implement new exercises, head over there and create an issue. Members of the rust track team are happy to help!

If you want to know more about Exercism, take a look at the contribution guide.

Wikipedia, 1024 bit key from www.cryptopp.com/wiki. http://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

```
use diffie_hellman::*;
#[test]
fn test_private_key_in_range_key() {
let primes: Vec<u64> = vec![
5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 773, 967, 3461, 6131,
];
let private_keys: Vec<u64> = primes.iter().map(|x| private_key(*x)).collect();
for i in 0..primes.len() {
assert!(1 < private_keys[i] && private_keys[i] < primes[i]);
}
}
#[test]
#[ignore]
fn test_public_key_correct() {
let p: u64 = 23;
let g: u64 = 5;
let private_key: u64 = 6;
let expected: u64 = 8;
assert_eq!(public_key(p, g, private_key), expected);
}
#[test]
#[ignore]
fn test_secret_key_correct() {
let p: u64 = 11;
let private_key_a = 7;
let public_key_b = 8;
let secret = secret(p, public_key_b, private_key_a);
let expected = 2;
assert_eq!(secret, expected);
}
#[test]
#[ignore]
fn test_public_key_correct_big_numbers() {
let p: u64 = 4_294_967_299;
let g: u64 = 8;
let private_key: u64 = 4_294_967_296;
let expected: u64 = 4096;
assert_eq!(public_key(p, g, private_key), expected);
}
#[test]
#[ignore]
fn test_secret_key_correct_big_numbers() {
let p: u64 = 4_294_967_927;
let private_key_a = 4_294_967_300;
let public_key_b = 843;
let secret = secret(p, public_key_b, private_key_a);
let expected = 1_389_354_282;
assert_eq!(secret, expected);
}
#[test]
#[ignore]
fn test_changed_secret_key() {
let p: u64 = 13;
let g: u64 = 11;
let private_key_a = private_key(p);
let private_key_b = private_key(p);
let public_key_a = public_key(p, g, private_key_a);
let public_key_b = public_key(p, g, private_key_b);
// Key exchange
let secret_a = secret(p, public_key_b, private_key_a);
let secret_b = secret(p, public_key_a, private_key_b);
assert_eq!(secret_a, secret_b);
}
```

```
extern crate rand;
use rand::prelude::*;
pub fn private_key(p: u64) -> u64 {
thread_rng().gen_range(1,p)
}
// https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method
fn mod_pow(mut base: u64, mut exp: u64, modulus: u64) -> u64 {
if modulus == 1 { return 0 }
let mut result = 1;
base = base % modulus;
while exp > 0 {
if exp % 2 == 1 {
result = result * base % modulus;
}
exp = exp >> 1;
base = base * base % modulus
}
result
}
pub fn public_key(p: u64, g: u64, a: u64) -> u64 {
mod_pow(g, a, p)
}
pub fn secret(p: u64, b_pub: u64, a: u64) -> u64 {
mod_pow(b_pub, a, p)
}
```

The mod_pow function is pretty neat. Explaining my understanding of the math here, since the wikipedia is a little terse:

We want to generate `b.pow(e) % m` (using rust as my LaTEX here ;)

We know that we can write _e_ as a binary number - say _e_ is `13`, then in binary it's `1011`. That's the same as writing it as a sum of powers of 2:

`1 * 2.pow(3) + 0 * 2.pow(2) + 1 * 2.pow(1) + 1 * 2.pow(0)`

Here's the trick - if we rewrite `b.pow(e)` substituting the above expression, we have

`b.pow(1 * 8 + 0 * 4 + 1 * 2 + 1 * 1)`

(this part is nicer with the sum notation)

From the way that exponents work, we can 'distribute' the sum in the exponent as a product. `2.pow(3) == 2.pow(1) * 2.pow(2)`

If we do that here, we get

`b.pow(8) * 1 * b.pow(2) * b.pow(1)`

Thats equivalent to `b.pow(13)`, which isn't really all that surprising - if you add up the powers, you get back to 13.

What's really cool about writing it this way, though, is that we can do the modulus operation for each of these powers of the base separately. That means we can do:

`(b.pow(8) % p) * (b.pow(2) % p) * (b.pow(1) % p)`

and that will be equivalent to `b.pow(13) % p`.

So, this algorithm uses this transformation to do modular exponentiation with _n_ steps, where _n_ is the number of bits in _e_ (log base 2 of e).

Now, what does this loop syntax actually do? In each step, it checks the smallest bit of _e_ to see whether that power of 2 'counts' - in our example where `e == 13 == 0b1011`, the first, second, and fourth bits will 'count' and the third bit (counting from the right) won't - it's a `0`. If that bit counts, then we accumulate that step into our result - we multiply by _b_ to the power of 2 times our loop step, modulo _p_. We right shift our exponent to look at the next bit, and raise _b_ to the next power of 2., modulo _p_.

It walks through the `b.pow(2 * i)`, multiplying by each one, depending on whether that bit in the exponent was set. It turns our formula into code!

https://en.wikipedia.org/wiki/Modular_exponentiation#Right-to-left_binary_method

Level up your programming skills with 3,126 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments

The mod_pow function is pretty neat. Explaining my understanding of the math here, since the wikipedia entry is a little terse.

We want to generate

`b.pow(e) % m`

(using rust as my LaTEX here ;)We know that we can write

eas a binary number - sayeis`11`

, then in binary it's`1011`

. That's the same as writing it as a sum of powers of 2:`1 * 2.pow(3) + 0 * 2.pow(2) + 1 * 2.pow(1) + 1 * 2.pow(0)`

Here's the trick - if we rewrite

`b.pow(e)`

substituting the above expression, we have`b.pow(1 * 8 + 0 * 4 + 1 * 2 + 1 * 1)`

(this part is nicer with the sum notation)

From the way that exponents work, we can 'distribute' the sum in the exponent as a product.

`2.pow(3) == 2.pow(1) * 2.pow(2)`

If we do that here, we get

`b.pow(8) * 1 * b.pow(2) * b.pow(1)`

Thats equivalent to

`b.pow(11)`

, which isn't really all that surprising - if you add up the powers, you get back to 11.What's really cool about writing it this way, though, is that we can do the modulus operation for each of these powers of the base separately. That means we can do:

`(b.pow(8) % m) * (b.pow(2) % m) * (b.pow(1) % m)`

and that will be equivalent to

`b.pow(11) % m`

.So, this algorithm uses this transformation to do modular exponentiation with

nsteps, wherenis the number of bits ine(log base 2 of e).Now, what does this loop syntax actually do? In each step, it

eto see whether that power of 2 'counts'. In our example where`e == 11 == 0b1011`

, the first, second, and fourth bits will 'count' and the third bit (from the right) won't - it's a`0`

.`result`

by the current power ofb, modulom. In our example, in the first loop step, this will be`b.pow(1) % m`

, then`b.pow(2) % m`

, [4 is skipped], then`b.pow(8) % m`

.bto the next power of 2 modulop, so that we're ready for the next step in our loop.For e = 11, our result starts at

`1`

, and the loops go:And then we have consumed all the bits of the exponent, so we're done.

The loop walks through the

`b.pow(2 * i)`

, multiplying by each one, depending on whether that bit in the exponent was set. It turns our formula into code!