Understanding the Diffie-Hellman key exchange calculator — concept and principle
Diffie-Hellman (DH) lets two parties who have never met agree on a shared secret over a channel that anyone can read. The shared secret is then turned into keys for encryption. This calculator uses small numbers so you can check each step by hand. Variants of the same idea run in every HTTPS connection today, usually on elliptic curves.
How it is calculated
Alice and Bob publicly agree on a prime p and a generator g. Then:
- Alice picks a secret a and sends A = gᵃ mod p.
- Bob picks a secret b and sends B = gᵇ mod p.
- Alice computes Bᵃ mod p; Bob computes Aᵇ mod p.
Both results equal g^(ab) mod p, which is the shared secret. The tool computes the powers with exact modular exponentiation and checks that both sides match.
The principle
Exponents multiply: (gᵇ)ᵃ = g^(ba) = (gᵃ)ᵇ, and this stays true when every step is reduced modulo p. An eavesdropper sees p, g, A and B but not a or b. Recovering a from A = gᵃ mod p is the discrete logarithm problem, and computing g^(ab) from gᵃ and gᵇ alone is believed to be just as hard for well-chosen large groups. In this toy group of 23 elements anyone can try all exponents; in a 2,048-bit group that is impossible in practice.
Worked example
- Inputs: p = 23, g = 5, Alice's a = 6, Bob's b = 15.
- A = 5⁶ mod 23 = 15,625 mod 23 = 8.
- B = 5¹⁵ mod 23 = 19.
- Alice: 19⁶ mod 23 = 2. Bob: 8¹⁵ mod 23 = 2.
- Shared secret = 2, and the check reads match.
| Alice secret a | Shared secret |
|---|---|
| 1.5 | 2 |
| 3 | 5 |
| 4.5 | 5 |
| 6 | 2 |
| 7.5 | 2 |
| 9 | 10 |
| 12 | 4 |
How to read the result
"match" confirms that both sides derived the same value, as the algebra guarantees for whole-number inputs. A good g should generate a large subgroup; with a poor g the possible secrets collapse to a few values. In real systems the shared value is never used directly but passed through a key derivation function such as HKDF.
Common mistakes
- Assuming DH alone stops a man-in-the-middle. Without authentication (certificates or signatures) an attacker can run separate exchanges with each side.
- Reusing secrets a and b across sessions, which removes forward secrecy.
- Choosing a or b as 0 or 1, which makes A equal to 1 or g.
Frequently asked questions
Who invented Diffie-Hellman?
Whitfield Diffie and Martin Hellman published it in 1976; Ralph Merkle contributed the underlying idea of public key agreement.
What is ECDH or X25519?
The same exchange done on an elliptic curve group. It gives comparable security with much smaller keys, so it is faster.
Does Diffie-Hellman encrypt messages?
No. It only agrees on a secret; a symmetric cipher such as AES then encrypts the data.
Sources: W. Diffie, M. E. Hellman, "New Directions in Cryptography", IEEE Transactions on Information Theory 22(6), 1976 · IETF RFC 7748, Elliptic Curves for Security