Asymmetric Encryption & Key Exchange
Symmetric encryption has one big problem: both sides need the same secret key. How do you agree on a key with a website you've never visited, over a network anyone can listen to? Asymmetric (public-key) cryptography solves this. Each party has a key pair:
- a public key that can be shared with everyone, and
- a private key that never leaves its owner.
Whatever the public key locks, only the private key opens. Public-key operations are slow, so in practice they are used to agree on or protect a symmetric key, which then encrypts the actual data. This is called hybrid encryption, and TLS, SSH, PGP and Signal all work this way.
| Algorithm | Used for | Based on |
|---|---|---|
| RSA | Encryption, signatures | Difficulty of factoring large numbers |
| Diffie-Hellman (DH) | Key agreement | Discrete logarithms |
| ECDH / X25519 | Key agreement (modern) | Elliptic curves |
| ECDSA / Ed25519 | Signatures | Elliptic curves |
| ML-KEM (Kyber) | Key agreement, post-quantum | Lattices |
RSA in miniature
RSA's maths is short enough to see in full. The example below uses tiny primes, so it is completely insecure: it only shows the structure. Real RSA uses primes of 1024+ bits (2048-bit or larger keys) and padding (OAEP).
# TOY RSA: INSECURE, for understanding only
p, q = 61, 53
n = p * q # public modulus
phi = (p - 1) * (q - 1)
e = 17 # public exponent
d = pow(e, -1, phi) # private exponent: e*d = 1 (mod phi)
print("public key (n, e):", (n, e))
print("private key (n, d):", (n, d))
message = 65 # a number smaller than n
ciphertext = pow(message, e, n)
recovered = pow(ciphertext, d, n)
print("encrypt", message, "->", ciphertext)
print("decrypt", ciphertext, "->", recovered)public key (n, e): (3233, 17)
private key (n, d): (3233, 2753)
encrypt 65 -> 2790
decrypt 2790 -> 65
Anyone can encrypt with (n, e). Decrypting needs d, and computing d requires phi, which requires the factors p and q. For n = 3233 that is trivial; for a 2048-bit n no known method can factor it in any useful time. That gap is the whole security of RSA.
Warning: "Textbook" RSA like this is also insecure for structural reasons: the same message always gives the same ciphertext, and ciphertexts can be manipulated mathematically. Real systems use a library with OAEP padding (
cryptography'srsaandpadding.OAEP), never hand-written RSA.
Diffie-Hellman key exchange
Diffie-Hellman lets two parties create a shared secret over a public channel without ever sending it. Each picks a private number, sends a public value, and combines the other's public value with their own private number. Here is the idea with small, insecure numbers:
# TOY Diffie-Hellman: INSECURE parameters, for understanding only
p = 23 # public prime
g = 5 # public generator
alice_private = 6
bob_private = 15
alice_public = pow(g, alice_private, p) # sent over the network
bob_public = pow(g, bob_private, p) # sent over the network
print("on the wire:", alice_public, bob_public)
alice_secret = pow(bob_public, alice_private, p)
bob_secret = pow(alice_public, bob_private, p)
print("Alice computes", alice_secret, "| Bob computes", bob_secret)on the wire: 8 19
Alice computes 2 | Bob computes 2
An eavesdropper sees p, g and both public values, but getting the secret requires solving a discrete logarithm, which is infeasible for properly sized parameters.
Plain Diffie-Hellman has one weakness: it doesn't say who you are talking to. An active attacker in the middle could run one exchange with Alice and another with Bob. That's why real protocols authenticate the exchange with signatures and certificates (next lessons).
X25519: modern key agreement
Today's systems use elliptic-curve Diffie-Hellman, usually X25519. The cryptography package makes it a few lines. Keys are random, so we print only sizes and whether both sides agree:
from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes, serialization
alice = X25519PrivateKey.generate()
bob = X25519PrivateKey.generate()
alice_pub = alice.public_key().public_bytes(serialization.Encoding.Raw,
serialization.PublicFormat.Raw)
print("public key size:", len(alice_pub), "bytes")
shared_a = alice.exchange(bob.public_key())
shared_b = bob.exchange(alice.public_key())
print("same shared secret:", shared_a == shared_b)
# Never use the raw shared secret as a key: derive one with a KDF
def derive(shared):
return HKDF(algorithm=hashes.SHA256(), length=32, salt=None,
info=b"demo chat v1").derive(shared)
print("same AES key:", derive(shared_a) == derive(shared_b))public key size: 32 bytes
same shared secret: True
same AES key: True
A 32-byte X25519 key gives security comparable to a 3,000-bit RSA key, which is why elliptic curves have largely replaced RSA for key exchange.
Forward secrecy
If a server encrypted session keys with its long-term RSA key, then anyone who stole that key later could decrypt recorded past traffic. With ephemeral Diffie-Hellman (a fresh key pair for every session, thrown away afterwards), stealing the long-term key reveals nothing about past sessions. This property is forward secrecy, and TLS 1.3 requires it.
Post-quantum cryptography
A large quantum computer could break RSA and elliptic-curve cryptography. Because data recorded today might be decrypted in the future ("harvest now, decrypt later"), new post-quantum algorithms such as ML-KEM are being deployed, typically in hybrid mode alongside X25519 so security holds as long as either one is unbroken. Symmetric algorithms like AES-256 and hashes like SHA-256 are much less affected.
Go further: Diffie–Hellman and the Man in the Middle steps through the exchange and Mallory's attack, and X25519 and Forward Secrecy covers the modern version.
Test yourself
In hybrid encryption, what does public-key cryptography usually protect?
- Every byte of data
- A symmetric key that then encrypts the data
- Only passwords
- The IP header
Why does plain Diffie-Hellman need to be combined with authentication?
- It is too slow alone
- Without it, an active attacker in the middle can run separate exchanges with each side
- It leaks the private numbers
- It only works on LANs
What does forward secrecy guarantee?
- Messages arrive in order
- Stealing a long-term key later doesn't decrypt previously recorded sessions
- Keys never expire
- Encryption is faster