SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 15

Cybersecurity Fundamentals · Lesson 15 of 90 · 15 min

Asymmetric cryptography and key exchange

public keyprivate keykey pairtrapdoor functionRSAmodulus and key sizeelliptic curve cryptography (ECC)curves (P-256, Curve25519)Diffie-HellmanECDHkey exchangeforward secrecyephemeral keyshybrid encryption

These are the notes for Cybersecurity Fundamentals (defensive), episode 15. Since episode 11, every demo started with Riya and Aman already sharing a secret AES key. Today we answer the question we kept skipping: how do two people who have never met agree on a key over a network everyone can hear? You'll invent each idea from a real-life problem: the key distribution problem, the public key, private key and key pair, the trapdoor function, RSA (its modulus and key size), Diffie-Hellman key exchange, elliptic curve cryptography (ECC) with the curves P-256 and Curve25519, ECDH, forward secrecy and ephemeral keys, hybrid encryption, key encapsulation (KEM), and why asymmetric crypto is slow. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Riya, Aman and the messages are made up. Every code sample runs with Python 3.13 and the cryptography package (version 50.0.1); outputs are real, copied from actual runs. Random keys and timings differ on every run; the toy-number demos print exactly the same values. In tracebacks, long file paths are shortened to just the file name. Toy demos with tiny numbers are for understanding only: never use them for real security.

The problems you'll solve

Problem Idea it teaches
Send the key over the network? Key distribution problem
A lock anyone can close Public key, private key, key pair, asymmetric cryptography
Easy one way, hard back Trapdoor function, factoring
Encrypt with a public key RSA: modulus, exponents, OAEP, key size
RSA is slow and small Why asymmetric is slow
Agree on a secret without sending it Diffie-Hellman, discrete logarithm
Smaller keys, same strength ECC, curves P-256 and Curve25519, ECDH, X25519
A key stolen next year Ephemeral keys, forward secrecy
Slow public keys + fast AES Hybrid encryption, HKDF, KEM

The one-line lesson: two keys, one secret: the public key locks, the private key unlocks.

Problem 1: the key distribution problem

Riya in Pune and Aman in Delhi have never met. They want to use AES-GCM (episode 12), which is symmetric: both sides need the same secret key. The obvious idea is for Riya to pick a random key and send it to Aman. But the network is open: an eavesdropper (someone who quietly listens to traffic) copies the key on the way and reads everything after.

This is the key distribution problem (episode 11): how do two parties who have never met agree on a secret over a channel that everyone can hear? Couriers and pre-shared keys don't scale to billions of people and websites.

Problem 2: public and private keys

Padlocks Asymmetric cryptography
Aman hands out open padlocks to anyone His public key: shared with the whole world
Only Aman's key opens them, and it never leaves his pocket His private key: kept secret, never sent
Riya snaps a padlock on a box and posts it Encrypt with the public key; only the private key decrypts

A key pair is a public key and a private key generated together and mathematically linked. Encrypting with one key and decrypting with a different one is asymmetric cryptography, also called public-key cryptography. Whitfield Diffie and Martin Hellman introduced the idea in their 1976 paper New Directions in Cryptography (they received the 2015 ACM Turing Award for it).

Problem 3: a trapdoor function

We need maths that is easy to do, very hard to undo, unless you know one secret. That secret is the trapdoor, and the whole thing is a trapdoor function.

One candidate: take two big prime numbers (numbers divisible only by 1 and themselves), p and q. Multiplying them is instant. But given only the product n, finding p and q (factoring) is very hard.

Demo 1: multiplying is easy, factoring is hard

import time

def factor(n):                     # the hard direction
    f = 3
    while n % f:
        f += 2
    return f, n // f

for p, q in [(10007, 10061), (1000003, 1000081),
             (10000019, 10000079)]:
    n = p * q                      # the easy direction
    t = time.perf_counter()
    factor(n)
    s = time.perf_counter() - t
    print(f"{len(str(n))}-digit n: factored in {s:.3f} s")

Output (timings vary):

9-digit n: factored in 0.000 s
13-digit n: factored in 0.065 s
15-digit n: factored in 0.274 s
  • n % f is the remainder of n ÷ f; the loop tries every odd divisor until the remainder is 0 (this is trial division).
  • Multiplying was instant every time; factoring time grows with every extra pair of digits.
  • Real RSA uses a 3,072-bit modulus, about 925 decimal digits. Attackers use far cleverer algorithms than trial division, but even the best known methods can't factor numbers that size.

Problem 4: RSA

In 1977 Ron Rivest, Adi Shamir and Leonard Adleman published the first practical public-key system, RSA, named after their initials (2002 ACM Turing Award).

Part What it is
p, q Two secret primes
n = p × q The modulus, public. Its length in bits is the key size
e The public exponent, usually 65537
d The private exponent, computable only from p and q
Public key (n, e)
Private key d (plus p, q)
Encrypt c = mᵉ mod n
Decrypt m = cᵈ mod n

mod n means "the remainder after dividing by n" (modular arithmetic, like a clock that wraps around).

Demo 2: toy RSA by hand

# TOY textbook RSA: tiny numbers, NEVER use for real
p, q = 61, 53
n = p * q                      # modulus: public
phi = (p - 1) * (q - 1)        # secret (needs p and q)
e = 17                         # public exponent
d = pow(e, -1, phi)            # private exponent

print("public key: (n, e) =", (n, e))
print("private key: d =", d)

m = 65                         # the message, as a number
c = pow(m, e, n)               # anyone can encrypt
print("ciphertext:", c)
print("decrypted: ", pow(c, d, n))   # only d decrypts

Output:

public key: (n, e) = (3233, 17)
private key: d = 2753
ciphertext: 2790
decrypted:  65
  • pow(m, e, n) computes mᵉ mod n quickly. pow(e, -1, phi) finds the modular inverse: the d with e × d mod phi = 1.
  • phi (Euler's totient of n) needs p and q. That's the trapdoor: without factoring n, nobody can compute d.

Demo 3: real RSA-3072 with OAEP, and its size limit

Textbook RSA (the bare formula above) is unsafe: the same message always gives the same ciphertext (see Practice 4), and ciphertexts can be manipulated. Real RSA encryption uses OAEP (Optimal Asymmetric Encryption Padding), a standard way to add randomness and structure before encrypting.

from cryptography.hazmat.primitives.asymmetric import (
    rsa, padding)
from cryptography.hazmat.primitives import hashes

key = rsa.generate_private_key(public_exponent=65537,
                               key_size=3072)
pub = key.public_key()          # share this with everyone
oaep = padding.OAEP(mgf=padding.MGF1(hashes.SHA256()),
                    algorithm=hashes.SHA256(), label=None)

ct = pub.encrypt(b"AES key: 7f3a...", oaep)
print(len(ct), "bytes of ciphertext")
print(key.decrypt(ct, oaep))    # only the private key
pub.encrypt(b"x" * 400, oaep)   # a big message?

Output:

384 bytes of ciphertext
b'AES key: 7f3a...'
Traceback (most recent call last):
  File "main.py", line 14, in <module>
    pub.encrypt(b"x" * 400, oaep)   # a big message?
    ~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
ValueError: Encryption failed
  • The ciphertext is always the size of the modulus: 3072 bits = 384 bytes.
  • RSA can only encrypt a message smaller than the modulus minus the padding. With OAEP-SHA256 that's 384 − 2×32 − 2 = 318 bytes. 400 bytes fails with ValueError: Encryption failed.
  • So RSA encrypts small things, like an AES key, never a file.

Key size and strength

Key Security strength (NIST SP 800-57)
RSA-2048 112 bits (the current minimum)
RSA-3072 128 bits (the same as AES-128)
ECC P-256 / Curve25519 about 128 bits

Security strength in bits means "about 2^bits operations to break": 128-bit strength means roughly 2¹²⁸ work.

Demo 4: why asymmetric is slow

import os, time
from cryptography.hazmat.primitives.asymmetric import (
    rsa, padding)
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives import hashes

def us(fn):                          # microseconds per call
    t = time.perf_counter()
    for _ in range(200): fn()
    return (time.perf_counter() - t) / 200 * 1e6

key = rsa.generate_private_key(public_exponent=65537,
                               key_size=3072)
oaep = padding.OAEP(mgf=padding.MGF1(hashes.SHA256()),
                    algorithm=hashes.SHA256(), label=None)
ct = key.public_key().encrypt(b"x" * 32, oaep)
gcm, n = AESGCM(os.urandom(16)), os.urandom(12)
c = gcm.encrypt(n, b"x" * 32, None)

print(f"RSA-3072: {us(lambda: key.decrypt(ct, oaep)):7,.0f} us")
print(f"AES-GCM:  {us(lambda: gcm.decrypt(n, c, None)):7,.0f} us")

Output (timings vary by machine):

RSA-3072:   2,257 us
AES-GCM:       16 us
  • us (microseconds, millionths of a second) times a function 200 times and averages. lambda makes a tiny unnamed function.
  • RSA decryption is hundreds of times slower than AES-GCM, because it does arithmetic on numbers hundreds of digits long, while AES uses a few fast operations, often built into the CPU.

Problem 5: Diffie-Hellman key exchange

RSA sends a key inside a locked box. Diffie and Hellman found something stranger: two people can create a shared secret without ever sending it.

Paint Diffie-Hellman
Both start with public yellow paint Public numbers p (a prime) and g (a generator)
Each secretly adds a colour and sends the mix Riya sends A = gᵃ mod p, Aman sends B = gᵇ mod p
Un-mixing paint is practically impossible Recovering a from A is the discrete logarithm problem
Each adds their own colour again: same brown Riya: Bᵃ mod p; Aman: Aᵇ mod p; both equal gᵃᵇ mod p

Demo 5: toy Diffie-Hellman

# TOY Diffie-Hellman: tiny numbers, NEVER use for real
p, g = 23, 5                 # public: everyone knows

a = 6                        # Riya's secret
b = 15                       # Aman's secret
A = pow(g, a, p)             # Riya sends A in public
B = pow(g, b, p)             # Aman sends B in public
print("on the wire: A =", A, " B =", B)

print("Riya computes:", pow(B, a, p))
print("Aman computes:", pow(A, b, p))

Output:

on the wire: A = 8  B = 19
Riya computes: 2
Aman computes: 2

Only 8 and 19 crossed the network; the shared secret 2 never did. With numbers thousands of bits long, finding 6 from 8 is as hard as factoring. Key exchange means two parties agreeing on a shared secret key over an open channel.

Problem 6: elliptic curves

RSA and classic Diffie-Hellman need 3,072-bit numbers for 128-bit strength. Elliptic curve cryptography (ECC) does the same jobs using points on a special curve instead of plain numbers: multiplying a point by a secret number is easy; going back from the result to the secret is hard.

Term Meaning
Curve A fixed, published set of parameters everyone agrees on
P-256 A curve standardised by NIST (also called secp256r1)
Curve25519 A curve designed by Daniel J. Bernstein, built on the prime 2²⁵⁵ − 19
ECDH Elliptic-curve Diffie-Hellman: Diffie-Hellman done on a curve
X25519 ECDH on Curve25519 (RFC 7748, January 2016): 32-byte keys, about 128-bit security

A 256-bit curve key gives about the strength of RSA-3072 with keys 12 times smaller. TLS 1.3, the protocol behind HTTPS, lists x25519 and secp256r1 among its key-exchange groups.

Demo 6: real X25519

from cryptography.hazmat.primitives.asymmetric.x25519 import (
    X25519PrivateKey)

riya = X25519PrivateKey.generate()
aman = X25519PrivateKey.generate()

# only the PUBLIC keys cross the network (32 bytes each)
riya_pub, aman_pub = riya.public_key(), aman.public_key()

s1 = riya.exchange(aman_pub)
s2 = aman.exchange(riya_pub)
print("Riya:", s1.hex()[:32])
print("Aman:", s2.hex()[:32])
print("same secret?", s1 == s2)

Output (random keys, yours will differ):

Riya: bdc487c27b668e43117e9f5fc187764c
Aman: bdc487c27b668e43117e9f5fc187764c
same secret? True

exchange combines your private key with the other side's public key. Both get the same 32-byte secret, which never crossed the network.

Problem 7: forward secrecy

An eavesdropper records years of encrypted traffic he can't read today. Next year the server's long-term private key is stolen (a breach, a lost backup). If every session key was sent locked with that one RSA key, he can now unlock every recording, all the way back.

The fix: for each session, both sides create a brand-new Diffie-Hellman key pair, use it once, and delete it. These are ephemeral keys (short-lived). A stolen long-term key reveals nothing about past sessions, because their secrets came from keys that no longer exist. That property is forward secrecy (also called perfect forward secrecy, PFS). In TLS 1.3, "static RSA and Diffie-Hellman cipher suites have been removed; all public-key based key exchange mechanisms now provide forward secrecy."

Problem 8: hybrid encryption

Public-key crypto solves key distribution but is slow and limited in size; AES is fast but needs a shared key. Hybrid encryption uses both:

 X25519 key exchange  ──►  HKDF  ──►  AES-GCM
 (slow, once, small)      (clean key)  (fast, gigabytes)
  1. A key exchange (X25519) agrees on a raw shared secret.
  2. HKDF (HMAC-based key derivation function) turns that raw secret into a clean, uniform AES key. Unlike password KDFs (episode 14) it is fast, because its input is already random.
  3. An AEAD (AES-GCM, episode 12) encrypts the actual data.

Steps 1-2 together form a key encapsulation mechanism (KEM): the sender produces a fresh key plus a small package (here an ephemeral public key) that only the receiver's private key can open. Modern standards, including the post-quantum ML-KEM in episode 27, are built as KEMs.

Demo 7: the whole recipe

import os
from cryptography.hazmat.primitives.asymmetric.x25519 import (
    X25519PrivateKey)
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def kdf(s): return HKDF(hashes.SHA256(), 32, None, b"v1").derive(s)
aman = X25519PrivateKey.generate()      # Aman's key pair

eph = X25519PrivateKey.generate()       # Riya: fresh, one message
key = kdf(eph.exchange(aman.public_key()))
nonce, data = os.urandom(12), b"a 2 GB video..." * 1000
ct = AESGCM(key).encrypt(nonce, data, None)
eph_pub = eph.public_key(); del eph     # send eph_pub, forget eph

key2 = kdf(aman.exchange(eph_pub))      # Aman: same key
print(len(ct), "bytes sent")
print(AESGCM(key2).decrypt(nonce, ct, None)[:15])

Output:

15016 bytes sent
b'a 2 GB video...'
  • HKDF(hashes.SHA256(), 32, None, b"v1"): SHA-256 inside, 32-byte output, no salt, and b"v1" as info (a label that ties the key to this purpose).
  • 15,000 bytes of data + a 16-byte tag = 15,016, plus one 32-byte public key.
  • del eph throws away the ephemeral private key. One slow step, then fast AES for any amount of data: the same idea HTTPS uses.

The next problem: the man in the middle

Plain Diffie-Hellman has a gap. An active attacker (one who can change traffic, not just read it) sends Riya his public key instead of Aman's, and does the same to Aman. He now shares one key with each of them and relays everything, reading it all: a man-in-the-middle (MITM) attack (episode 10; Practice 5 shows it). Riya needs proof that a public key really belongs to Aman: a digital signature and a certificate, next episode.

The whole chain

Step Problem Invention
1 Sending the key leaks it Key distribution problem
2 A lock anyone can close Public key, private key, key pair
3 Easy one way, hard back Trapdoor function, factoring
4 Encrypt with a public key RSA, OAEP, key size
5 RSA is slow and small Use it only for small things
6 Agree without sending Diffie-Hellman, discrete log
7 Smaller keys ECC, P-256, Curve25519, ECDH, X25519
8 A key stolen next year Ephemeral keys, forward secrecy
9 Slow + fast together Hybrid encryption, HKDF, KEM
? Whose public key is it? Signatures and certificates (episode 16)

Common mistakes (and what they print)

Mistake What you see Why Fix
pub.encrypt(400-byte file, oaep) ValueError: Encryption failed RSA-3072 + OAEP fits only 318 bytes Hybrid: encrypt the data with AES-GCM
Textbook RSA (no padding) Same message → same ciphertext Deterministic and malleable RSA-OAEP, or better, X25519 + AEAD
RSA-1024 or tiny primes Below the 112-bit minimum Factorable with enough effort RSA-3072 or a 256-bit curve
Raw DH/ECDH secret used directly as the AES key Uneven, structured key bytes A shared secret isn't a uniform key Run it through HKDF
Reusing one long-term key pair for every session Old recordings readable after a key theft No forward secrecy Ephemeral keys per session
Trusting a public key that arrived unauthenticated A MITM reads everything Key exchange alone doesn't prove identity Signatures and certificates (episode 16)

Mini project: a tiny "sealed box"

Anyone with Aman's public key can seal a message that only Aman can open, with a fresh ephemeral key per message (forward secrecy for the sender's side) and AES-GCM for integrity.

import os
from cryptography.hazmat.primitives.asymmetric.x25519 import (
    X25519PrivateKey, X25519PublicKey)
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.exceptions import InvalidTag

RAW = serialization.Encoding.Raw, serialization.PublicFormat.Raw

def derive(shared, eph_pub_bytes, recipient_pub_bytes):
    info = b"sealbox-v1" + eph_pub_bytes + recipient_pub_bytes
    return HKDF(hashes.SHA256(), 32, None, info).derive(shared)

def seal(recipient_pub, message):
    eph = X25519PrivateKey.generate()               # fresh per message
    eph_pub = eph.public_key().public_bytes(*RAW)
    rcpt = recipient_pub.public_bytes(*RAW)
    key = derive(eph.exchange(recipient_pub), eph_pub, rcpt)
    nonce = os.urandom(12)
    return eph_pub + nonce + AESGCM(key).encrypt(nonce, message, None)

def open_box(my_key, box):
    eph_pub, nonce, ct = box[:32], box[32:44], box[44:]
    shared = my_key.exchange(X25519PublicKey.from_public_bytes(eph_pub))
    rcpt = my_key.public_key().public_bytes(*RAW)
    return AESGCM(derive(shared, eph_pub, rcpt)).decrypt(nonce, ct, None)

aman = X25519PrivateKey.generate()
box = seal(aman.public_key(), b"meet at the chai stall at 6")
print(len(box), "bytes = 32 eph key + 12 nonce + 27 msg + 16 tag")
print(open_box(aman, box))
print(seal(aman.public_key(), b"same") != seal(aman.public_key(), b"same"))

eve = X25519PrivateKey.generate()
try:
    open_box(eve, box)
except InvalidTag:
    print("Eve can't open it: InvalidTag")

Output:

87 bytes = 32 eph key + 12 nonce + 27 msg + 16 tag
b'meet at the chai stall at 6'
True
Eve can't open it: InvalidTag
  • public_bytes(Raw, Raw) turns a public key into its 32 raw bytes so it can be sent.
  • Both public keys go into the HKDF info, binding the derived key to this exact exchange.
  • Sealing the same text twice gives different boxes (fresh ephemeral key and nonce).
  • Eve's private key derives a different AES key, so GCM's tag check fails with InvalidTag.
  • This mirrors the design of real "sealed box" / HPKE-style constructions; in production use a vetted library API (for example libsodium's crypto_box_seal) rather than your own.

Practice

1. Homework: toy RSA with p = 101, q = 113. Find a valid e, compute d, and round-trip two messages.

Solution
p, q = 101, 113
n, phi = p * q, (p - 1) * (q - 1)
e = 3
while True:                          # e must share no factor with phi
    from math import gcd
    if gcd(e, phi) == 1: break
    e += 2
d = pow(e, -1, phi)
print("n =", n, " e =", e, " d =", d)
for m in (42, 1234):
    c = pow(m, e, n)
    print(m, "->", c, "->", pow(c, d, n))

Output:

n = 11413  e = 3  d = 7467
42 -> 5610 -> 42
1234 -> 10345 -> 1234

gcd is the greatest common divisor; e must have gcd(e, phi) = 1 or no inverse d exists. Messages must be smaller than n.

2. Homework: time bigger RSA keys. Compare decryption speed for 2048, 3072 and 4096 bits.

Solution
import time
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import hashes

oaep = padding.OAEP(mgf=padding.MGF1(hashes.SHA256()),
                    algorithm=hashes.SHA256(), label=None)
for bits in (2048, 3072, 4096):
    key = rsa.generate_private_key(public_exponent=65537, key_size=bits)
    ct = key.public_key().encrypt(b"x" * 32, oaep)
    t = time.perf_counter()
    for _ in range(100):
        key.decrypt(ct, oaep)
    ms = (time.perf_counter() - t) / 100 * 1000
    print(f"RSA-{bits}: {ms:.2f} ms per decryption, {bits // 8}-byte ciphertext")

Output (timings vary):

RSA-2048: 0.70 ms per decryption, 256-byte ciphertext
RSA-3072: 2.22 ms per decryption, 384-byte ciphertext
RSA-4096: 5.04 ms per decryption, 512-byte ciphertext

Doubling the key size makes private-key operations roughly 7-8 times slower, one reason ECC took over.

3. Why toy Diffie-Hellman is breakable. The eavesdropper sees p = 23, g = 5, A = 8. Find Riya's secret.

Solution
# The eavesdropper sees p=23, g=5, A=8 and tries every secret
p, g, A = 23, 5, 8
for a in range(1, p):
    if pow(g, a, p) == A:
        print("Riya's secret could be", a)

Output:

Riya's secret could be 6

With a tiny p there are only 22 candidates. Real Diffie-Hellman uses p of 2048+ bits (or a 256-bit curve), making this search impossible.

4. Why textbook RSA leaks. A vote is yes (89) or no (78), encrypted with textbook RSA (n, e) = (3233, 17). Can an eavesdropper tell which?

Solution
# Textbook RSA (no padding) is deterministic: same message, same ciphertext
n, e = 3233, 17
votes = {"yes": 89, "no": 78}            # votes encoded as numbers
seen = pow(votes["yes"], e, n)           # a ciphertext on the wire
for word, m in votes.items():
    if pow(m, e, n) == seen:
        print("the eavesdropper knows the vote:", word)

Output:

the eavesdropper knows the vote: yes

With few possible messages, anyone can encrypt each guess with the public key and compare. OAEP's randomness stops this.

5. Homework: why can't plain Diffie-Hellman stop a man in the middle?

Solution
# A man in the middle against unauthenticated toy Diffie-Hellman
p, g = 23, 5
a, b, m = 6, 15, 13                      # Riya, Aman, Mallory's secrets
A, B, M = pow(g, a, p), pow(g, b, p), pow(g, m, p)
# Mallory swaps both public values for his own M
riya_key = pow(M, a, p)                  # Riya thinks this is with Aman
aman_key = pow(M, b, p)                  # Aman thinks this is with Riya
print("Riya-Mallory key:", riya_key, "| Mallory computes", pow(A, m, p))
print("Aman-Mallory key:", aman_key, "| Mallory computes", pow(B, m, p))

Output:

Riya-Mallory key: 18 | Mallory computes 18
Aman-Mallory key: 7 | Mallory computes 7

Nothing in the exchange proves who sent A or B, so Mallory shares a key with each side and relays (and reads) everything. Authenticating the public values with signatures fixes this (episode 16).

6. Pick the tool. (a) Encrypt a 5 GB backup for a colleague who published a public key. (b) Two servers set up a fresh session key every connection. (c) Encrypt a 32-byte AES key for a system that only supports RSA.

Solution

(a) Hybrid encryption: an ephemeral X25519 exchange + HKDF + AES-GCM (or a vetted tool built on that). (b) Ephemeral ECDH (X25519) for forward secrecy, authenticated with certificates. (c) RSA-OAEP with at least a 3072-bit key.

Quick quiz

A server uses fresh (ephemeral) X25519 keys for every session. Next year its long-term key is stolen. What stays safe?

A. Nothing, everything is exposed B. Only future sessions C. Past recorded sessions D. Only the password database

Answer

C. Each session's secret came from ephemeral keys that were deleted. The stolen long-term key never protected those secrets, so old recordings stay unreadable. That's forward secrecy.

Interview questions

  1. What's the difference between symmetric and asymmetric encryption? Symmetric uses one shared key (AES), fast but needs key distribution; asymmetric uses a key pair (RSA, ECC), slower but the public key can be shared openly.
  2. What is a trapdoor function? Give an example. Easy to compute, hard to invert unless you know a secret: multiplying two large primes is easy, factoring the product is hard, unless you know the primes (RSA).
  3. Why do we use hybrid encryption? Asymmetric operations are hundreds of times slower and can only handle small inputs, so we use them to agree on (or wrap) a symmetric key, then encrypt data with an AEAD.
  4. How does Diffie-Hellman work, and what's its weakness? Both sides exchange gᵃ and gᵇ publicly and each computes gᵃᵇ; security rests on the discrete logarithm problem. Unauthenticated, it's vulnerable to a man-in-the-middle.
  5. What is forward secrecy? Compromise of long-term keys doesn't expose past session keys, achieved with ephemeral (EC)DH keys deleted after use. TLS 1.3 key exchanges all provide it.
  6. Why prefer ECC over RSA? Equal security with much smaller keys and faster operations: a 256-bit curve ≈ RSA-3072 at 128-bit strength.
  7. What is OAEP and why is textbook RSA unsafe? A randomised padding scheme for RSA encryption. Textbook RSA is deterministic (guessable messages can be confirmed) and malleable.
  8. What is a KEM? A key encapsulation mechanism: it outputs a fresh shared key plus an encapsulation only the recipient can open; post-quantum ML-KEM is one.

Glossary

Term Meaning in plain words Example
Symmetric encryption One shared key both encrypts and decrypts AES-GCM
Key distribution problem How to share a secret key with someone over an open channel Riya and Aman have never met
Eavesdropper Someone who quietly reads traffic Copies a key sent in the open
Asymmetric (public-key) cryptography Encrypting with one key, decrypting with another RSA, ECC
Public key The half of a key pair you share with everyone aman.public_key()
Private key The half you keep secret X25519PrivateKey.generate()
Key pair A public and a private key generated together Aman's padlocks and key
Prime number A number divisible only by 1 and itself 61, 53, 1000003
Factoring Finding the primes that multiply to a number 3233 = 61 × 53
Trapdoor function Easy to compute, hard to undo unless you know a secret Multiplying primes
Trial division Factoring by trying divisors one by one Demo 1
RSA Public-key system by Rivest, Shamir and Adleman (1977), based on factoring RSA-3072
Modulus n = p × q, the public number in RSA; its bit length is the key size 3233 in the toy
Key size The length of the modulus (or curve) in bits 3072 bits = 384 bytes
Public / private exponent e (public) and d (private) in RSA 17 and 2753
Modular arithmetic / mod Working with remainders after division pow(m, e, n)
Modular inverse The number d with e × d mod phi = 1 pow(e, -1, phi)
Textbook RSA The bare RSA formula with no padding; unsafe Practice 4
OAEP Randomised padding for RSA encryption padding.OAEP(...)
Security strength Bits of work to break: 128-bit ≈ 2¹²⁸ operations RSA-3072 = 128-bit
Diffie-Hellman (DH) Two parties create a shared secret from public exchanges (1976) Paint mixing
Generator (g) The public base number in DH g = 5
Discrete logarithm problem Finding a from gᵃ mod p; hard for big p Why DH is safe
Key exchange Agreeing on a shared secret over an open channel X25519
Elliptic curve cryptography (ECC) Public-key crypto using points on a curve; small keys Curve25519
Curve The fixed public parameters of an ECC system P-256, Curve25519
P-256 NIST's 256-bit curve (secp256r1) In TLS 1.3
Curve25519 Bernstein's curve over the prime 2²⁵⁵ − 19 Used by X25519
ECDH Diffie-Hellman on an elliptic curve X25519
X25519 ECDH on Curve25519 (RFC 7748), 32-byte keys riya.exchange(aman_pub)
Long-term key A key kept for months or years A server's certificate key
Ephemeral key A key pair made for one session, then deleted eph in Demo 7
Forward secrecy Stolen long-term keys don't expose past sessions TLS 1.3
Hybrid encryption Asymmetric crypto for the key, symmetric crypto for the data X25519 + HKDF + AES-GCM
HKDF HMAC-based key derivation function: turns a shared secret into clean keys HKDF(hashes.SHA256(), 32, None, b"v1")
Info (HKDF) A label that ties a derived key to its purpose b"sealbox-v1"
KEM Key encapsulation mechanism: fresh key + a package only the recipient can open DHKEM, ML-KEM
Microsecond (us) One millionth of a second RSA ≈ 2,000 us
Man-in-the-middle (MITM) An attacker who sits between two parties and relays or changes traffic Swapping public keys
Digital signature Proof that a specific private key signed some data (episode 16) Fixes MITM
Certificate A signed statement binding a public key to a name (episode 16) HTTPS certificates

Summary

  • Symmetric crypto needs a shared key; sending it in the open is the key distribution problem.
  • Asymmetric crypto uses a key pair: the public key locks (or verifies), the private key unlocks (or signs).
  • It rests on trapdoor functions: multiplying primes is easy, factoring is hard (RSA); exponentiation is easy, the discrete log is hard (Diffie-Hellman).
  • RSA: use OAEP, at least 3072 bits (2048 is the 112-bit minimum). It only encrypts small things and is slow.
  • Diffie-Hellman creates a shared secret that is never sent. ECC (P-256, Curve25519) gives the same strength with small keys; X25519 is ECDH on Curve25519.
  • Ephemeral keys give forward secrecy: past sessions survive a future key theft.
  • Real systems use hybrid encryption: key exchange → HKDF → AES-GCM; the first part is a KEM.
  • Plain key exchange can't detect a man in the middle: that needs signatures and certificates.

Next episode: digital signatures and PKI: signatures, RSA-PSS, ECDSA, Ed25519, certificates, certificate authorities, chains of trust, revocation, Certificate Transparency and Let's Encrypt.

Sources: ACM, "Cryptography Pioneers Receive 2015 ACM A.M. Turing Award" (1 Mar 2016) on Diffie and Hellman's 1976 paper; ACM A.M. Turing Award profile of Ronald Rivest (RSA, 1977; award 2002); RFC 7748, Elliptic Curves for Security (Jan 2016); NIST SP 800-57 Part 1 Rev. 5 key-strength tables, as reproduced by AQtive Guard; IETF draft-ietf-tls-rfc8446bis-14 (TLS 1.3), section 1.3 and supported groups. Code outputs from Python 3.13 with cryptography 50.0.1. Fetched 29 Oct 2026.