Key Exchange and Diffie-Hellman

Key Exchange

Symmetric encryption needs both sides to hold the same key. In the old days that key was handed over physically or read out by voice. Today a server has to establish one across the internet, where anything sent can be intercepted.
The solution is key exchange: an algorithm that allows two computers to agree on a key without sending one.
Read that twice, because it is the part that sounds impossible. The key is never transmitted. Both computers finish holding the same number, and no message containing that number ever crosses the network.
This is done using one-way functions. A one-way function is a function that is easy to compute but hard to invert. Mixing paint is the everyday example: it is easy to mix two colours together, and very hard to unmix them, meaning to work out which colours went in from the colour that came out.

Two people, one secret colour each

Alice and Bob want to establish a shared secret key for encryption and decryption. Eve is listening to everything they send. She is called Eve because she eavesdrops.
Here is the whole method in four steps. Both of them do all four.
• Step 1. Each starts with a secret colour and shows it to nobody.
• Step 2. Each mixes the public colour into their own secret colour.
• Step 3. Each sends that mixture to the other, out in the open, where Eve sees it.
• Step 4. Each mixes their own secret colour into the mixture that just arrived.
Key exchange with paint, in three columns: Alice, In the open, Bob. Eve sees all of the middle column. 1. Each picks a secret colour: Alice's secret is red, the public colour is yellow, Bob's secret is blue. 2. Each mixes in the public colour: public plus Alice's is orange, public plus Bob's is grey-green. 3. Each sends the mixture: the orange from Alice and the grey-green from Bob cross the open middle. 4. Each adds their own secret: Alice and Bob each end with the same brownish shared colour. Both buckets: public plus Alice's plus Bob's. Same colour.
In the paint storyIn Diffie-HellmanWho sees it
The public colour both mix inThe base B and the modulus MEveryone, agreed in the open
Alice's secret colourAlice's secret exponent XAlice only, never sent
Bob's secret colourBob's secret exponent YBob only, never sent
Mixing two colours togetherRaising to a power, then reducing modulo MNot a value, an operation
The mixture each one sendsThe number each one computes at step 2Everyone, Eve records both
The colour both end up withThe shared keyAlice and Bob only, never sent

Congruent modulo n

Diffie-Hellman key exchange uses modular exponentiation as its one-way function. First, a piece of notation for it.
Two positive integers x and y are congruent modulo n when they leave the same remainder on division by n. In JavaScript that test is x % n === y % n.
For example 7 and 2 are congruent modulo 5, since both of them leave a remainder of 2 when divided by 5. This is written 7 = 2 mod 5, with an equals sign that means congruent rather than equal.
When we perform operations here we reduce modulo n, so that every result is a remainder somewhere from 0 to n minus 1.

Why modular exponentiation is one-way

Modular exponentiation means raising a base to a power and then reducing the result modulo n. It is a one-way function because it is easy to raise a power but hard to invert.
Going forwards is one line:
console.log((3 ** 5) % 31);   // prints 26
That line is honest at this size and quietly wrong at any real one. JavaScript holds whole numbers exactly only up to 9007199254740991, and a power runs past that almost at once, after which the remainder comes back wrong with nothing to warn you. Written as a single expression, (3 ** 40) % 17 prints 0. The right answer is 16.
The repair is to reduce at every step, so the running value never climbs past the modulus:
function modPow(base, exponent, modulus) {
let result = 1;
for (let i = 0; i < exponent; i = i + 1) {
result = (result * base) % modulus;
}
return result;
}
console.log(modPow(3, 40, 17)); // prints 16
Going backwards is the problem. Finding the exponent x for which 3 raised to the power x is congruent to 26 modulo 31 is called the discrete logarithm problem, and no efficient algorithm for it is known. With a modulus this small you can just try every exponent in turn until one matches. In real use the base is often small (2 is a common choice), and the modulus is a large prime hundreds of digits long. At that size, trying every exponent is not something any computer will finish, and the cleverer methods that are known are still far too slow.

The Diffie-Hellman key exchange

The process is the painting example with arithmetic in place of colours. Alice and Bob agree publicly on two numbers, a base B and a modulus M. Eve sees both of them.
• Step 1. Alice picks a secret exponent X. Bob picks a secret exponent Y. Neither one is ever sent.
• Step 2. Alice computes B to the power X, modulo M. Bob computes B to the power Y, modulo M. Each is a single call to the helper above, modPow(B, X, M).
• Step 3. Alice sends her result to Bob, and Bob sends his result to Alice, in the open.
• Step 4. Each raises the number that arrived to their own secret exponent, modulo M. For Alice that is modPow(received, X, M).
Alice has now raised B to the power Y, and then raised all of that to the power X. Bob has raised B to the power X, and then raised all of that to the power Y. Both are B raised to the power X times Y, modulo M, so both land on the same number. That number is the shared key.
Diffie-Hellman with base 3, modulus 17, in three columns: Alice, In the open, Bob. Eve records all of the middle column. 1. Each picks a secret exponent: Alice's secret X = 15; public: base 3, mod 17; Bob's secret Y = 13. 2. Each raises the base to the secret: Alice, 3 to the 15, mod 17 = 6; Bob, 3 to the 13, mod 17 = 12. 3. Each sends the result: 6 from Alice, 12 from Bob, in the open. 4. Each raises what arrived to the secret: Alice, 12 to the 15, mod 17 = 10; Bob, 6 to the 13, mod 17 = 10; shared key. Both get 10. Eve saw 3, 17, 6 and 12, never 10.
The program below runs the exchange between a phone and a server, with base 6 and modulus 79. It starts with the modPow helper from above, and every calculation in the exchange is a call to it. Then it plays the eavesdropper: it tests the exponents 1, 2, 3, and upward until one gives the number the phone sent. With a modulus this small, that search ends almost at once. Run it, then change it and run it again:
• Change serverSecret to another whole number from 1 to 100.
• Change phoneSecret to 71.
• Press Reset, then change modPow(base, phoneSecret, modulus) to (base ** phoneSecret) % modulus, the single expression that comes back wrong once the power is large, and compare the two keys.
function modPow(base, exponent, modulus) {
  let result = 1;
  for (let i = 0; i < exponent; i = i + 1) {
    result = (result * base) % modulus;
  }
  return result;
}

let base = 6;
let modulus = 79;
let phoneSecret = 37;
let serverSecret = 55;

let phoneSends = modPow(base, phoneSecret, modulus);
let serverSends = modPow(base, serverSecret, modulus);
console.log("The phone sends", phoneSends);
console.log("The server sends", serverSends);

let phoneKey = modPow(serverSends, phoneSecret, modulus);
let serverKey = modPow(phoneSends, serverSecret, modulus);
console.log("Phone's key:", phoneKey);
console.log("Server's key:", serverKey);

// The eavesdropper tries every exponent until one gives what the phone sent
let guess = 1;
while (modPow(base, guess, modulus) !== phoneSends) {
  guess = guess + 1;
}
console.log("The eavesdropper finds an exponent that gives what the phone sent:", guess);
Output
Press Run to see what this program prints.

Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.

Two shortcomings

One shortcoming of the Diffie-Hellman key exchange is the communication overhead it takes to establish a shared key. Alice and Bob have to send the results of their calculations back and forth before a single word of the actual message can be encrypted.
Another is that the exchange only sets up one key, between two people. If Alice needs to message different people, she needs to exchange a different key with each of them. A key that several people hold protects nothing between them, since each of them could decrypt what the others send. If she is a bank, she needs thousands of distinct keys, one per customer, and thousands of exchanges to set them all up before any of them can carry a message.