Cryptography & Security
Advanced

Diffie–Hellman Shared Secret

Two parties derive the same secret over a public channel.

Formula

s=Ba mod ps = B^a \bmod p

Variables

sShared secret
BOther party's public value
aYour private key
pPrime modulus

Example

B=8, a=15, p=23: s = 8^15 mod 23 = 2

How it works

In Diffie–Hellman key exchange, you take the other party’s public value B and raise it to your private exponent a modulo a large prime p to produce the shared secret s. This works because both parties are really computing the same modular power in different orders, and modular exponentiation preserves the equality that comes from the commutative structure of the underlying group. The security comes from the difficulty of recovering a private exponent from the public values when p is large and chosen properly.

When to use it

Use this when two systems need to agree on a secret key over an insecure network without sending that key directly. It appears in key exchange protocols, secure messaging setup, and any cryptographic system that relies on establishing a shared symmetric key from public information.

Worked example, step by step

Given B = 19, a = 11, p = 29 s = B^a mod p s = 19^11 mod 29 19^2 = 361 ≡ 13 mod 29 19^4 ≡ 13^2 = 169 ≡ 24 mod 29 19^8 ≡ 24^2 = 576 ≡ 25 mod 29 19^11 = 19^(8+2+1) ≡ 25 × 13 × 19 mod 29 25 × 13 = 325 ≡ 6 mod 29 6 × 19 = 114 ≡ 27 mod 29 Therefore, s = 27

Common mistakes to avoid

  • Using the public value from the wrong party or confusing B with your own public value
  • Forgetting the modulus, which makes the computation far too large and breaks the group arithmetic
  • Assuming the exponent itself is the shared secret instead of the modular exponentiation result

Did You Know?

Diffie–Hellman (1976) was the first published way for strangers to agree a secret in public — the birth of modern crypto.

Share this formula

Reviewed & maintained by the FormulaWon editorial teamLast reviewed September 2026