Imagine two people who have never met, standing at opposite ends of a crowded hall. Everything they say can be heard by everyone in the room, and yet, after a few sentences, both of them know the same secret number and nobody else in the hall does. That sounds impossible, because it seems that to share a secret you must, at some point, say it. In 1976 two researchers, Whitfield Diffie and Martin Hellman, published a way to do exactly this. Their method, now called Diffie-Hellman key exchange, quietly runs every time a browser, a phone app or an artificial intelligence (AI) agent opens a protected connection. This article builds the whole idea from nothing. You will see the arithmetic it relies on, run a complete exchange with numbers small enough to check by hand, watch why someone listening cannot finish the calculation, and then watch the method fail in a very specific way when an attacker can change the messages instead of only hearing them. That last part matters most, because it explains why key agreement on its own never tells you who you are talking to.

The problem: agreeing on a secret in public

Most protection on the internet uses a key: a secret value that turns readable data into scrambled data and back again. The fastest kind of encryption, called symmetric encryption, uses the same key on both ends. It is like a padlock with two identical copies of its key, one for each person. Symmetric encryption is quick and strong, but it has an awkward starting problem. Before two computers can use it, both must hold the same key, and they usually have no private way to hand that key over. The only road between them is the internet, where messages can be copied by anyone along the path.

Before 1976 the answer was physical. Organisations sent keys by courier, loaded them onto devices in person, or agreed them at a meeting. That works for a handful of embassies. It cannot work for billions of devices that meet each other for the first time every second. What was needed was a way for two parties to build the same secret together, out loud, so that a listener who hears every word still ends up without it.

A familiar way to picture the trick uses paint. Two friends agree in public on a common starting colour, say yellow. Each then picks a private colour that they never reveal: one picks red, the other picks blue. Each mixes their private colour into a pot of yellow and sends the mixture across the room. Now each friend adds their own private colour to the pot they received. The first friend has yellow, blue and red; the second has yellow, red and blue. Same three ingredients, so the same final colour. Anyone watching saw plain yellow and the two mixtures, but unmixing paint to recover the private colours is, in practice, hopeless.

Diffie-Hellman replaces paint with numbers, and replaces 'mixing' with a kind of arithmetic that is easy to do forwards and very hard to undo. The rest of the method follows from that one property, so it is worth understanding the arithmetic before anything else.

📌
Agreement, not delivery. Nothing secret ever travels between the two sides; each side computes the shared secret for itself from what it keeps and what it receives.

Clock arithmetic and a step that is hard to undo

Think of a clock. If it is 9 o'clock and you wait 5 hours, the clock shows 2, not 14, because the numbers wrap around after 12. Mathematicians call this modular arithmetic, and the number where it wraps around is the modulus. On a 12-hour clock the modulus is 12. You can build a clock with any number of positions. Diffie-Hellman uses a clock whose number of positions is a prime number, a whole number that cannot be divided evenly by anything except 1 and itself, such as 23.

On a 23-position clock, every calculation ends by taking the remainder after dividing by 23. For example, 30 on this clock is 7, because 30 divided by 23 leaves 7 over. Write that as '30 mod 23 = 7', where 'mod' means 'the remainder after dividing by'. The answer is always a number from 0 to 22.

Now take a starting number, called the generator, and multiply it by itself over and over on this clock. With a generator of 5 and a modulus of 23, the first few steps are: 5, then 5 times 5 is 25 which wraps to 2, then 2 times 5 is 10, then 10 times 5 is 50 which wraps to 4, then 4 times 5 is 20, and so on. Multiplying a number by itself a certain number of times is called raising it to a power, or exponentiation, and the count of multiplications is the exponent. So '5 to the power 4, mod 23' means 'take 5, multiply by 5 three more times, and keep wrapping around 23', and the answer is 4.

Here is the property everything rests on. Going forwards is easy: give a computer a generator, a modulus and an exponent, and it can find the result almost instantly, even for numbers hundreds of digits long, using a shortcut called repeated squaring that needs only a few thousand multiplications. Going backwards is hard: give someone the generator, the modulus and the result, and ask which exponent produced it, and for large enough numbers nobody knows a practical way to answer. This backwards question has a name, the discrete logarithm problem. 'Discrete' because we only use whole numbers, and 'logarithm' because finding an exponent is what a logarithm does in ordinary maths.

On a tiny 23-position clock you can solve the backwards question by simply trying every exponent, because there are only 22 possibilities. That is exactly why real systems use clocks whose modulus has hundreds of digits. The step stays just as easy forwards, but the number of possibilities to try grows so large that trying them all would take longer than the age of the universe, and the cleverer methods mathematicians have found are still far too slow at those sizes.

The exchange, step by step

Let us name the two parties Alice and Bob, which is the tradition in cryptography. Before anything secret happens, they agree on two public numbers: the modulus p and the generator g. These can be shouted across the hall, published in a standard, or built into software. Everyone, including any eavesdropper, is allowed to know them. In our example p is 23 and g is 5.

Step one: each side picks a private number and tells no one. Alice picks a, Bob picks b. These private numbers are the 'private colours' from the paint story. Step two: each side raises the generator to its private number on the clock. Alice computes A, which is g to the power a, mod p. Bob computes B, which is g to the power b, mod p. A and B are the 'mixtures', and they are safe to send, because recovering a from A is the hard backwards question. Step three: Alice sends A to Bob and Bob sends B to Alice, in the open.

Step four is the clever part. Alice takes the number she received, B, and raises it to her own private number a. Bob takes A and raises it to his private number b. Alice is computing g to the power b, then to the power a. Bob is computing g to the power a, then to the power b. Both are just g multiplied by itself a times b times, so they arrive at exactly the same number. That number is the shared secret. It was never sent; each side built it from one thing it kept and one thing it received.

Only the public numbers and the two mixtures cross the open channel; each side finishes the calculation privately. One exchange in four moves Alice keeps a = 6 Open channel anyone can listen Bob keeps b = 15 1. agree p = 23, g = 5 2. A = 5^6 mod 23 = 8 2. B = 5^15 mod 23 = 19 3. sends A = 8 3. sends B = 19 4. 19^6 mod 23 = 2 4. 8^15 mod 23 = 2 Both now hold 2, and the number 2 never crossed the channel
Only the public numbers and the two mixtures cross the open channel; each side finishes the calculation privately.
  1. Agree in public on a prime modulus p and a generator g.
  2. Each side picks a private number and keeps it secret.
  3. Each side sends g raised to its private number, mod p.
  4. Each side raises what it received to its own private number; both results match.

A complete exchange you can check by hand

Numbers make this real, so here is the whole exchange with the small values above. Alice's private number is 6 and Bob's is 15. Every step uses the 23-position clock.

Alice's public mixture: 5 to the power 6. Five squared is 25, which wraps to 2. Squaring again gives 5 to the power 4, which is 2 times 2, or 4. Then 5 to the power 6 is 5 to the power 4 times 5 squared, so 4 times 2, which is 8. Alice sends A = 8.

Bob's public mixture: 5 to the power 15. We already know 5 squared is 2 and 5 to the power 4 is 4. Squaring again, 5 to the power 8 is 4 times 4, which is 16. Since 15 is 8 plus 4 plus 2 plus 1, Bob multiplies 16, 4, 2 and 5 together: that is 640, and 640 on a 23-position clock is 19, because 23 times 27 is 621 and 640 minus 621 leaves 19. Bob sends B = 19.

Alice finishes: she raises 19 to her private 6. A neat trick helps here: 19 is 4 less than 23, so on this clock it behaves like minus 4. Minus 4 to the power 6 is 4096, and 4096 wraps to 2, because 23 times 178 is 4094. Alice's result is 2.

Bob finishes: he raises 8 to his private 15. Eight is 2 times 2 times 2, so this is 2 to the power 45. On this clock, 2 to the power 11 happens to equal 2048, which wraps to exactly 1. That means every block of eleven 2s collapses to 1, and 45 is four blocks of 11 with 1 left over, so the answer is simply 2. Bob's result is also 2.

Both sides now hold the number 2, and neither ever sent it. An eavesdropper heard 23, 5, 8 and 19. To get the secret, the eavesdropper needs either Alice's 6 or Bob's 15, which means answering 'which power of 5 gives 8?' or 'which power of 5 gives 19?'. On a clock this small you could find 6 by trial in seconds. On a real clock you could not.

The toy exchange in one view; the private rows never leave each side.
ValueWho knows itNumber
Modulus p and generator gEveryone23 and 5
Alice's private number aAlice only6
Bob's private number bBob only15
Alice's public mixture AEveryone8
Bob's public mixture BEveryone19
Shared secretAlice and Bob only2
⚠️
Learning numbers only. A 23-position clock protects nothing; real exchanges use a modulus of at least 2048 bits, which is a number over 600 decimal digits long, or an elliptic-curve version with equivalent strength.

What the listener sees, and why the listener is stuck

It helps to stand in the eavesdropper's shoes. The listener records every message: the modulus, the generator, and both public mixtures. The listener even knows the exact method, because Diffie-Hellman is a published standard. Security does not come from hiding how it works. It comes only from the two private numbers, which never leave their owners.

From the public values, the most obvious attack is to recover one private number by solving the discrete logarithm problem, then finish the calculation exactly as that side would have. For a properly chosen modulus of 2048 bits or more, the best known methods for doing this on ordinary computers are far beyond any realistic budget. Another tempting idea is to combine the two public mixtures directly. Multiplying 8 by 19, or adding them, does not give the shared secret; the secret needs one private number in the calculation, and the listener has neither. The assumption that nobody can compute the shared secret from the public values alone is known as the computational Diffie-Hellman assumption.

Real deployments add care that the toy example skips. The modulus is not just any prime; standard bodies publish carefully generated groups, which are the sets of numbers the clock produces, so that the backwards problem is uniformly hard and the generator does not get trapped in a short loop of repeating values. A widely used family of these groups is defined in Request for Comments (RFC) 7919, a published internet standard. Many systems now use the same idea on elliptic curves, a different kind of mathematical clock that reaches the same strength with much smaller numbers. The steps of the exchange are the same: pick a private number, send a public mixture, combine what you receive with what you kept.

There is one more thing the listener cannot do, and it is worth stating plainly: a passive listener cannot change anything. That word 'passive' is the hinge of the whole security story. A listener who can only hear is defeated by the arithmetic. An attacker who can also speak, by intercepting and replacing messages, is a completely different problem, and the arithmetic alone does nothing to stop it.

Agreement is not identity: the substituted message

Go back to the crowded hall. Alice shouts her mixture towards Bob, but a third person, Mallory, is standing between them and can catch messages in mid-air and shout replacements. Alice cannot see Bob; she only hears a voice that says it is Bob. This kind of attacker, one who sits on the path and can read, drop and replace messages, is called a man-in-the-middle, or on-path, attacker.

Mallory picks her own private number, 3, and computes her own mixture: 5 to the power 3 is 125, which wraps to 10 on the 23-position clock. When Alice sends 8, Mallory catches it and sends 10 to Bob instead. When Bob sends 19, Mallory catches it and sends 10 to Alice instead. Neither Alice nor Bob can tell, because 10 is a perfectly ordinary-looking number.

Now everyone finishes the calculation. Alice raises 10 to her private 6 and gets 6. Mallory raises Alice's 8 to her own private 3: 8 cubed is 512, which wraps to 6. So Alice and Mallory share the number 6. Bob raises 10 to his private 15 and gets 5. Mallory raises Bob's 19 to her private 3: 19 behaves like minus 4, minus 4 cubed is minus 64, and minus 64 wraps to 5. So Bob and Mallory share the number 5.

The result is two separate secure-looking connections, Alice to Mallory and Mallory to Bob. Mallory can decrypt everything Alice sends, read or alter it, re-encrypt it with the key she shares with Bob, and pass it on. Both victims believe they have a private line to each other. The arithmetic worked perfectly; it simply worked with the wrong person. That is the central lesson of this article: Diffie-Hellman gives you a secret shared with whoever is on the other end of the exchange, and on its own it says nothing about who that is.

The fix is to bind the exchange to an identity. In real protocols, at least one side signs its public mixture, or the whole conversation so far, using a long-term signing key whose public half is vouched for by a certificate, an electronic document that a trusted authority has signed to say 'this key belongs to this name'. If Mallory replaces Bob's mixture, she cannot produce Bob's signature over the replacement, and the exchange fails loudly instead of succeeding silently. Combining key agreement with this kind of proof is called authenticated key exchange.

Mallory swaps each public mixture for her own, so each victim ends up sharing a different secret with her instead of with each other. The substituted message Open network path Alice shares 6 with Mallory Mallory on-path attacker Bob shares 5 with Mallory Two secrets 6 and 5, both hers sends 8, gets 10 sends 19, gets 10 keeps both believes it is talking to Bob believes it is talking to Alice
Mallory swaps each public mixture for her own, so each victim ends up sharing a different secret with her instead of with each other.
⚠️
A silent failure. Unauthenticated Diffie-Hellman does not fail with an error under attack; both sides complete the exchange and simply share their secrets with the attacker.

From a shared number to working keys

The shared secret is not used directly as an encryption key. It is a large number with some mathematical structure, and it has exactly one value per exchange. Protocols instead feed it, together with other details of the conversation, into a key derivation function, a one-way recipe that stirs its inputs into fresh, uniform-looking bytes and can produce several separate keys from one input. A common choice is HMAC-based Key Derivation Function (HKDF), standardised in RFC 5869. The output becomes the actual traffic keys: typically one key for each direction, so that a message from Alice to Bob and a message from Bob to Alice never use the same key.

The second habit of real systems is to use fresh private numbers for every connection and delete them as soon as the traffic keys exist. A private number used once and thrown away is called ephemeral. This gives a property called forward secrecy: if an attacker records an encrypted conversation today and steals one side's long-term keys next year, the recording still cannot be decrypted, because the private numbers that produced that conversation's secret no longer exist anywhere. The long-term key only ever signed the exchange; it never contributed to the secret.

Version 1.3 of Transport Layer Security (TLS), the protocol behind the padlock in a browser and behind most machine-to-machine connections, requires this ephemeral style for its standard handshakes: every full connection runs a fresh Diffie-Hellman exchange, either on a classic modular clock or, far more commonly, on an elliptic curve. Older protocols allowed static, reused Diffie-Hellman keys or skipped it entirely, which is one reason old configurations are retired.

Deleting secrets sounds trivial and is not. A private number that lingers in a log file, a crash dump or a debugging trace undoes forward secrecy for that connection. Well-built libraries handle this inside their own code, which is one of many reasons not to implement the exchange yourself.

The raw shared number is stirred with the conversation details into separate keys, and the private numbers are erased. Secret to traffic keys Fresh privatenumbers one per connection Shared secret same on both sides Key derivation for example HKDF Traffic keys one per direction Erase privatenumbers forward secrecy exchange with transcript expand then delete Nothing left to steal later
The raw shared number is stirred with the conversation details into separate keys, and the private numbers are erased.

What this means for practitioners and for AI agents

For most people, Diffie-Hellman is never something you call directly. It happens inside TLS, inside Secure Shell (SSH) for remote logins, inside messaging apps and inside virtual private networks. The practical decisions are about which settings you allow and what you check around the exchange, not about the arithmetic. Two questions do most of the work: is the exchange authenticated, so you know who is on the other end, and is it ephemeral, so that stolen keys cannot unlock yesterday's traffic?

AI agents raise the stakes on both questions. An agent is software that uses a language model to decide on actions and then calls tools to carry them out: it reads a mailbox, queries a database, or calls another agent. Every one of those calls is a network connection, usually protected by TLS, and every one starts with a key agreement. An agent that accepts any certificate, or a test setting that turns certificate checking off and is then shipped to production, is exactly the Mallory scenario: the encryption is real, the arithmetic is sound, and the agent is talking privately to whoever intercepted it. Because agents act on what they receive, an on-path attacker does not just read the data; it can feed the agent false tool results or altered instructions.

Agents also tend to run for a long time and talk to many endpoints, which makes the long-lived secrets around them valuable. Forward secrecy limits the damage when one of those secrets leaks: recorded agent traffic stays closed even after a later compromise. That only holds if the connection actually negotiated an ephemeral exchange and if nothing in the agent's telemetry captures key material. Debug options that export session keys for traffic inspection exist in common tools; they are useful in a lab and dangerous in production.

The checklist that follows is deliberately short. None of it requires understanding modular arithmetic, and all of it follows from the two lessons above: agreement needs identity, and secrets should be fresh and short-lived.

Only an exchange that is both authenticated and ephemeral protects today's traffic from impostors and yesterday's traffic from later key theft. Two questions, four outcomes Not authenticated Authenticated Ephemeral fresh keys Reused static keys Ephemeral only fresh keys, wrong partner Both the standard to require Neither impostor wins outright Authenticated only safe now, exposed later Left to right: is the other side proven? Top to bottom: are the private numbers fresh?
Only an exchange that is both authenticated and ephemeral protects today's traffic from impostors and yesterday's traffic from later key theft.
  • Require certificate and host-name checking on every agent and tool connection; treat any setting that disables it as a defect.
  • Prefer TLS 1.3, where every standard handshake uses a fresh, ephemeral exchange.
  • Never log, export or persist session keys or private exchange values outside a controlled lab.
  • Use well-maintained libraries and published groups or curves; never pick your own prime or write the exchange yourself.
  • When an agent calls another agent or a tool server, confirm which identity each side proves, not just that the channel is encrypted.

Key takeaways

  • Diffie-Hellman lets two parties compute the same secret while every message they exchange is public; the secret itself is never sent.
  • It relies on clock arithmetic where raising a number to a power is easy but recovering the power, the discrete logarithm, is impractical for large numbers.
  • A passive listener is defeated by the arithmetic, but an on-path attacker who substitutes messages ends up sharing a secret with each side.
  • Agreement is not identity: real protocols sign the exchange so a substituted message is detected instead of silently accepted.
  • Fresh, ephemeral private numbers that are deleted after use give forward secrecy, so later key theft cannot unlock recorded traffic.
  • For AI agents, the practical controls are certificate checking on every tool call, TLS 1.3, and never leaking session keys into logs.

Glossary

Symmetric encryption
Encryption where the same secret key locks and unlocks the data on both ends.
Modular arithmetic
Arithmetic on a clock: results wrap around and keep only the remainder after dividing by a fixed number, the modulus.
Generator
The public starting number that each side raises to its private power in a Diffie-Hellman exchange.
Discrete logarithm problem
The hard backwards question of finding which power of the generator produced a given result on the clock.
Man-in-the-middle (on-path) attacker
An attacker on the network path who can read, drop and replace messages, not just listen to them.
Authenticated key exchange
Key agreement combined with proof of identity, usually a signature backed by a certificate, so substituted messages are detected.
Key derivation function
A one-way recipe that turns a shared secret into several separate, uniform-looking keys.
Ephemeral key
A private value used for one connection only and deleted afterwards.
Forward secrecy
The property that stealing long-term keys later cannot decrypt traffic that was recorded earlier.

Further reading

  1. New Directions in Cryptography (W. Diffie and M. Hellman, IEEE Transactions on Information Theory, 1976)
  2. RFC 7919: Negotiated Finite Field Diffie-Hellman Ephemeral Parameters for TLS (IETF)
  3. RFC 8446: The Transport Layer Security (TLS) Protocol Version 1.3 (IETF)
  4. NIST SP 800-56A Rev. 3: Recommendation for Pair-Wise Key-Establishment Schemes Using Discrete Logarithm Cryptography