December 02, 2015

The beauty of Diffie-Hellman protocol

Last day I was thinking with a friend of mine a simple way to encrypt credentials in a Rest API with Basic Auth, the conversation continued and we ended up studying this fascinating protocol (the way an algorithm should be used) called “The Diffie-Hellman protocol”.

The Diffie-Hellman protocol (due to Whitfield Diffie and Martin Hellman) is a key-agreement protocol between two parts without previous contact, using an unsafe channel and without authentication.

It’s usually implemented as a way to obtain symmetric keys that will be used to encrypt some data (in our case the HTTP header). It’s security lies in the difficulty of computing discrete logarithms in a finite body.

This is a diagram showing the usage of that protocol:

Note: There is no need to pass p and g from A to B, it could be agreed before between the parts.


For example, Alice thinks two numbers: p and g, being p a prime number and g a number usually between 2 and 5, after that she thinks a random number a (a < p) to do that:

A = ga mod p

She sends g, p and A to Bob. (View the note in the image footer).

When Bob receives the data he thinks a random number b (b < p) and computes that:

B = gb mod p

Then, he sends B back to Alice.

When Alice receives the answer from Bob, she does that:

K = Ba mod p

and Bob does that:

J = Ab mod p

K and J will be equals, so there is the shared and symmetric private key.

I hope you’ve enjoyed this algorithm as much as I.