The Diffie-Hellman algorithm is used to establish a shared secret between two parties that can be used for secret communication to exchange data over a public network.

Pictorial Explanation:

The process begins by having the two parties, Alice and Bob, agree on an arbitrary starting color that does not need to be kept secret (but should be different every time); in this example, the color is yellow. Each of them selects a secret color–red and aqua, respectively–that they keep to themselves. The crucial part of the process is that Alice and Bob now mix their secret color with their mutually shared color, resulting in orange and blue mixtures, respectively, then publicly exchange the two mixed colors. Finally, each of the two mixes together the color they received from the partner with their own private color. The result is a final color mixture (brown) identical to the partner’s color mixture.

 
Diffie-Hellman_Key_Exchange

It would be impossible for eavesdropper Eve to determine the common secret color.

Cryptographic Explanation:

The algorithm in itself is very simple. Let’s assume that Alice wants to establish a shared secret with Bob. Here’s an example of the protocol with secret values in red.

  1. Alice and Bob agree to use a prime number p = 23 and base g = 5. (These two values are chosen in this way to ensure that the resulting shared secret can take on any value from 1 to p–1).
  2. Alice chooses a secret integer a = 6, then sends Bob A = ga mod p (A = 56 mod 23 = 8)
  3. Bob chooses a secret integer b = 15, then sends Alice B = gb mod p (B = 515 mod 23 = 19)
  4. Alice computes s = Ba mod p (s = 196 mod 23 = 2)
  5. Bob computes s = Ab mod p (s = 815 mod 23 = 2)
  6. Alice and Bob now share a secret (the number 2).

The number Alice get at step 4 is the same as Bob got in step 5 as

Bob computes

Ab mod p = (ga mod p)b mod p = gab mod p

 
Alice computes

Ba mod p = (gb mod p)a mod p = gba mod p

 
The Diffie-Hellman algorithm is primarily used to exchange cryptography keys for use in symmetric encryption algorithms like AES. Please note that information is not shared during the key exchange. Here the two parties are creating a key together.

 
Implementation:

C


Download  Run Code

Output:

Alice’s secret key is 2
Bob’s secret key is 2

That’s all about the Diffie-Hellman algorithm.

 
Reference: https://en.wikipedia.org/wiki/Diffie%E2%80%93Hellman_key_exchange