Diffie-Hellman Key Exchange Explainer

Enter prime p, generator g, and two private keys to see every step of Diffie-Hellman key exchange, including public keys and the derived shared secret.

Use the Diffie-Hellman Key Exchange Explainer

Parameters

Must be prime. Try 23, 47, 97, 257.

Primitive root mod p. Try 5 for p=23.

Private Keys

Quick Presets

Set parameters on the left and click Compute Key Exchange

Summary

Diffie-Hellman (DH) key exchange lets two parties establish a shared secret over an untrusted channel without ever sending the secret itself. This explainer walks through every arithmetic step — computing public keys via modular exponentiation and deriving the identical shared secret from each side — so you can see exactly why the math works. Use small numbers to follow along, or choose larger primes for a realistic simulation.

How it works

  1. Choose a public prime p and generator g (a primitive root mod p).
  2. Each party picks a private key (a secret integer smaller than p).
  3. Each party computes their public key: g raised to their private key, mod p.
  4. The parties exchange public keys over the (potentially insecure) channel.
  5. Each party raises the other's public key to their own private key, mod p.
  6. Both sides arrive at the same shared secret — proven by the math below.

Use cases

  • Learn how TLS/HTTPS establishes session keys without pre-shared secrets.
  • Understand why intercepting only public keys does not reveal the shared secret.
  • Verify your understanding of modular arithmetic and discrete logarithms.
  • Teach or study public-key cryptography with concrete numeric examples.
  • Prepare for security certification exams that cover key-exchange protocols.
  • Explore why small primes are insecure compared to 2048-bit DH groups.

Frequently Asked Questions

Last updated: 2026-06-11 · Reviewed by Nham Vu