Skip to content
Trapdoor·Lab

Diffie–Hellman: from mixing paint to ECDH

1Toy

A shared secret over an open channel

In 1976 Diffie and Hellman showed how two parties can agree on a shared secret over a channel anyone can eavesdrop on. Each party sends only its public key and computes the secret locally from its own private key and the other party’s public key — the secret itself never crosses the network. Classic DH computes powers modulo p, where p is a large prime, while ECDH instead multiplies a point on an elliptic curve by a number and gets by with much shorter keys: for 128-bit security NIST SP 800-57 (Part 1, Table 2) lists 3072-bit keys for DH modulo p and 256-bit keys on the curve.

Toy implementation — not for production useNumbers mod 23 break in a fraction of a second. Real DH: groups of at least 2048 bits (RFC 7919) or elliptic curves, like P-256 below.

Diffie–Hellman: mixing paint

The paint is only an analogy: mixing is easy, separating a mix back into its parts is very hard. Under every paint is real Diffie–Hellman arithmetic, just on toy-sized numbers.

Public parameters: the prime p = 23 and the generator g = 5. All arithmetic is modulo p — what counts is the remainder after dividing by 23.

Step 1 of 4 · Alice and Bob openly agree on a shared paint: yellow. In numbers that is p = 23 and g = 5 — known to everyone, eavesdropping Eve included.

Public channel
yellow — shared p = 23, g = 5

Paint and small numbers show the principle; below, the same exchange runs for real: your browser agrees on ECDH over the P-256 curve with this site’s server, and the server sends back a message encrypted with AES-GCM under a key derived with HKDF.

ECDH with this site’s server

A real key exchange on the P-256 curve: your browser (WebCrypto) and this site’s server (.NET) agree on a shared secret while sending each other only public keys.

Over the network, in the clear

  • public keys: yours and the server’s
  • a salt for HKDF and a nonce for AES-GCM
  • the ciphertext with its tag
  • the server’s fingerprint — first 8 B of SHA-256(Z), for this toy only

Never leaves its own side

  • private keys: yours and the server’s
  • the shared secret Z and the AES key derived from it

Start with a P-256 key pair. The private key is created in this browser as a non-extractable CryptoKey.

2Break it

Mallory in the middle

Diffie–Hellman alone does not tell you who is on the other end: in the “Break it” mode of the toy above, Mallory swaps the public keys in both directions and agrees one secret with you and a separate one with the server. The secret fingerprints on the two sides differ, but nobody compares them, so Mallory reads and alters the message and then encrypts it under the key agreed with you — you decrypt it without an error, because the AES-GCM tag checks out. The fix is to authenticate the exchange: in TLS 1.3 the server signs the handshake, including both ECDHE keys, with its certificate key (the CertificateVerify message), and in messengers you compare key fingerprints over another channel, for example by scanning a QR code. A large enough quantum computer running Shor’s algorithm will solve the discrete logarithm — modulo p and on the curve — and recover the secret from an exchange recorded today; a hybrid of X25519 with the post-quantum ML-KEM, which Chrome already offers, protects against that.

3In the real world

Where ECDH runs

  • TLS 1.3The parties exchange one-time (EC)DHE public keys in the key_share extension, and every compliant implementation must support key agreement on the P-256 curve (secp256r1) and should also support X25519.Source (TLS 1.3)
  • TLS 1.3 — CertificateVerifyThe server signs, with its certificate key, a hash of the handshake from the ClientHello onwards, and so both key_share values too, which is why a swapped ECDHE key fails signature verification.Source (TLS 1.3 — CertificateVerify)
  • Signal — PQXDHThe PQXDH protocol, an extension of X3DH, derives the session key with a KDF from three or four DH exchanges on Curve25519 or Curve448 plus a secret from a post-quantum KEM, and you confirm who you are talking to by comparing key fingerprints or scanning a QR code.Source (Signal — PQXDH)
  • WireGuardWireGuard sets up a tunnel with a Noise_IK handshake using ECDH on Curve25519 and repeats it every few minutes to rotate keys and keep forward secrecy.Source (WireGuard)
  • SSHIn SSH’s ECDH key exchange both sides generate one-time key pairs, the server signs the exchange hash with its host key, and a client that accepts the host key without checking it is defenceless against an active attack.Source (SSH)
  • ChromeSince version 131, Chrome offers a hybrid X25519 + ML-KEM-768 exchange (group code 0x11EC) in key_share — ECDH combined with the post-quantum ML-KEM.Source (Chrome)
4Take it to your project

Fresh keys, a KDF and authentication

Good practice

Generate a new key pair for every session and delete it once the key is agreed — then a later key leak does not expose recorded conversations (forward secrecy). The shared secret is the x-coordinate of a point, not uniformly random bytes, so pass it through a KDF, such as HKDF with a salt and context in info. Authenticate the exchange: sign your public key or the whole exchange with a long-term key, as the server does in TLS 1.3, or compare fingerprints over another channel. Load the other party’s key with a library import that checks the point lies on the curve — in WebCrypto importKey throws a DataError for a point off the curve.

JavaScript
// a new key pair for every session
const mine = await crypto.subtle.generateKey(
  { name: 'ECDH', namedCurve: 'P-256' }, false, ['deriveBits']);
// a point off the curve → DataError
const peer = await crypto.subtle.importKey(
  'raw', peerBytes, { name: 'ECDH', namedCurve: 'P-256' }, false, []);
const shared = await crypto.subtle.deriveBits(
  { name: 'ECDH', public: peer }, mine.privateKey, 256);
// the raw secret only as HKDF input
const ikm = await crypto.subtle.importKey(
  'raw', shared, 'HKDF', false, ['deriveKey']);
const key = await crypto.subtle.deriveKey(
  { name: 'HKDF', hash: 'SHA-256', salt, info },
  ikm, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']);
C#
using var mine = ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);
using var peer = ECDiffieHellman.Create();
// a point off the curve → exception
peer.ImportSubjectPublicKeyInfo(peerSpki, out _);
using var peerKey = peer.PublicKey;
byte[] shared = mine.DeriveRawSecretAgreement(peerKey);
byte[] key = HKDF.DeriveKey(HashAlgorithmName.SHA256, shared, 32, salt, info);
Anti-pattern

Do not use the raw shared secret as a key — the .NET documentation says outright that the output of DeriveRawSecretAgreement belongs in a KDF. Do not accept a point without validation: in an invalid-curve attack the attacker sends points off the curve and extracts the private key piece by piece — Jager, Schwenk and Somorovsky (2015) recovered this way the long-term key of a TLS server that used the Oracle or Bouncy Castle libraries. Do not keep one key pair for all sessions, and do not trust an exchange nobody has authenticated: until someone has checked a signature or a fingerprint, Mallory may be on the other end.

JavaScript
// ✕ the raw ECDH secret used directly as an AES key
const key = await crypto.subtle.importKey(
  'raw', shared, 'AES-GCM', false, ['encrypt', 'decrypt']);
C#
// ✕ one key pair for all sessions: if it leaks,
// every conversation recorded earlier is exposed too
static readonly ECDiffieHellman ServerKey =
    ECDiffieHellman.Create(ECCurve.NamedCurves.nistP256);