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 protocolbetween two parts without previous contact, using an unsafe channel and without authentication.It’s usually implemented as a way to obtain

symmetric keysthat 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 = g^{a} 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 = g^{b} mod p

Then, he sends B back to Alice.

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

K = B^{a} mod p

and Bob does that:

J = A^{b} 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.