Diffie-Hellman Key Exchange Simulator — Public Key Math
Pick a public prime p and generator g, choose private keys for Alice and Bob, and watch them reach the same shared key over an insecure channel. A small-numbers demo to build intuition for public-key cryptography.
Parameters
Prime p (public)
—
Generator g (public)
—
Alice's secret a
—
Bob's secret b
—
If a non-prime is entered for p, it is automatically snapped to the nearest prime. This is an educational demo — production systems should use p of at least 2048 bits, or ECDH.
Results
—
Alice's public A=g^a mod p
—
Bob's public B=g^b mod p
—
Alice's shared key K=B^a mod p
—
Bob's shared key K=A^b mod p
Key Exchange Flow
Left: Alice / Center: Public Channel (p, g) / Right: Bob. Arrows show public values traveling between parties.
Theory & Key Formulas
Diffie-Hellman key exchange lets two parties agree on a shared secret over an insecure channel, using only a public prime p and generator g.
Alice and Bob each pick a private key a or b and compute their public values:
$$A = g^{a} \bmod p, \qquad B = g^{b} \bmod p$$
Each side raises the partner's public value to their own secret to obtain the same shared key:
$$K_{\text{Alice}} = B^{a} \bmod p = A^{b} \bmod p = K_{\text{Bob}}$$
This works because the exponent law $(g^a)^b = (g^b)^a = g^{ab}$ also holds in a finite field mod p:
$$K = g^{ab} \bmod p$$
An eavesdropper who knows only p, g, A and B must solve the discrete logarithm problem to recover a or b, which is computationally hard for sufficiently large p.
What is the Diffie-Hellman Key Exchange Simulator
🙋
I have heard of "public-key cryptography", but how can two people encrypt their traffic without first meeting to share a key? If they send the key over a tapped line, it is meaningless, right?
🎓
Sharp question. The first answer was the 1976 Diffie-Hellman key exchange. Roughly speaking, the two of them publicly agree on a prime p and a generator g. Alice picks a secret number a and sends A = g^a mod p. Bob picks his own b and sends B = g^b mod p. Then both can compute the same value g^(ab) mod p. Try p=23, g=5, a=6, b=15 in the simulator above and you get A=8, B=19, and shared key K=2.
🙋
Wait, A and B are sent in the open? Can't an eavesdropper just compute the key from those?
🎓
That is exactly the trick. Even knowing p, g, A, and B, the eavesdropper has to solve the "discrete logarithm problem" to recover a from A. For a large prime p that is wildly hard. The simulator only handles p ≤ 997, so in reality you could brute-force a in microseconds. Production systems use p of 2048 bits or more — only then is it computationally infeasible.
🙋
I see. But why do Alice's K_A and Bob's K_B end up the same?
🎓
Just exponent rules. $(g^a)^b = (g^b)^a = g^{ab}$ — that holds in ordinary math, and it still holds for exponentiation mod p. Alice raises B = g^b to her a, getting (g^b)^a = g^(ab); Bob raises A = g^a to his b, getting (g^a)^b = g^(ab). Same result. Try varying a and b in the simulator: K_A and K_B always match.
🙋
So with Diffie-Hellman alone, encrypted communication is bulletproof?
🎓
Sadly, plain DH is wide open to "man-in-the-middle" attacks. An attacker can impersonate Alice to Bob and Bob to Alice, completing two separate key exchanges. So real systems combine DH with authentication: signing the public values, server certificates in TLS, fingerprint verification in messaging apps. TLS's ECDHE is the canonical example.
Frequently Asked Questions
When p is prime, the powers g^1, g^2, ..., g^(p-1) mod p take every nonzero value below p exactly once if g is a generator (primitive root). This maximizes the space of possible private keys a, making brute force harder for an attacker. With a composite p or a g of small order, the space of possible shared keys shrinks and security drops.
In production, a and b are random integers of at least 256 bits. This educational simulator caps them at 1 to 100 to be tangible, but at that size brute force breaks the scheme instantly. The crucial point is that fresh random keys are generated for each session — fixed keys mean a future leak compromises all past traffic (loss of forward secrecy).
ECDH applies the same Diffie-Hellman idea to point addition on an elliptic curve instead of integer exponentiation mod p. The advantage is that comparable security is reached with much smaller keys. Where classic DH needs around 2048 bits, ECDH gives equivalent or stronger security with about 256 bits. On phones, IoT devices and other resource-constrained platforms, ECDH is the de facto standard.
Direct use is not recommended. In practice, K is fed through a "key derivation function" (KDF, such as HKDF) to derive purpose-specific keys (encryption, authentication, IVs, etc.). This isolates compromise of one key from the others, removes any statistical bias in K, and yields well-mixed pseudo-random output suitable for cryptographic primitives.
Real-World Applications
HTTPS and TLS: The TLS protocol that secures HTTPS uses ECDHE (ephemeral elliptic-curve Diffie-Hellman) as its key-agreement scheme. The server is authenticated by a certificate, and a fresh per-session key is exchanged via DH so that even if the server's long-term private key leaks in the future, past traffic remains undecryptable. This property is called forward secrecy.
VPNs (IPsec, WireGuard): Corporate remote-access VPNs and the modern WireGuard protocol both rely on Diffie-Hellman key exchange to generate fresh tunnel keys. WireGuard uses ECDH over Curve25519, establishing a secure tunnel in just a couple of round-trips with very little overhead.
End-to-end encryption in Signal and WhatsApp: Messenger apps that promise end-to-end encryption use the Signal Protocol's "Double Ratchet", which performs a fresh DH exchange for nearly every message. Even if one message key leaks, neither past nor future messages can be decrypted in cascade.
SSH and general encrypted transport: SSH session setup also uses Diffie-Hellman key exchange. The fact that the client and server need no pre-shared secret to derive a fresh per-session key is one reason SSH became the default tool for remote server administration.
Common Misconceptions and Cautions
The most common misconception is to assume that "once you have exchanged a key with Diffie-Hellman, the channel is automatically secure". Plain DH is defenseless against man-in-the-middle attacks: an attacker who interposes between Alice and Bob can complete two separate exchanges, one with each side, and read everything. Real systems always pair DH with some form of authentication — server certificates in TLS, known-host keys in SSH, identity-key fingerprints in Signal — to verify that the partner is really who they claim to be.
The second pitfall is to assume the small primes used in this educational demo would be safe in production. With p ≤ 997 the attacker can simply try a = 1, 2, 3, ... until g^a mod p matches the public value A and recover the private key in microseconds. Real deployments use a prime p of at least 2048 bits (over 600 decimal digits) for classic DH, or about 256-bit elliptic-curve parameters for ECDH. Security depends exponentially on the size of p, so a compromise on key size is catastrophic.
Finally, beware of the misconception that "reusing the same private keys a and b is fine". If the same private key is reused across many sessions, then a single compromise of any one session key cascades back and decrypts every other session derived from that long-term secret. Real systems use ephemeral keys (the "E" in DHE/ECDHE stands for ephemeral): a fresh random a and b is generated for every session and immediately destroyed afterwards, securing forward secrecy.