C program to demonstrate Diffie-Hellman algorithm

Diffie-Hellman algorithm is used to establish a shared secret between two parties which can be used for secret communication for exchanging 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 together with their mutually shared color, resulting in orange and blue mixtures respectively, then publicly exchange the two mixed colors. Finally, each of the two mix together the color they received from the partner with their own private color. The result is a final color mixture (brown) that is identical to the partner’s color mixture.


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 is 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 same as Bob got at 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


Diffie-Hellman algorithm is primarily used as a method of exchanging 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.


Download   Run Code


Alice’s Secret Key is 2
Bob’s Secret Key is 2

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

Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂