Under the Hood
Crypto

Public-key cryptography: the two-key trick

Public-key cryptography replaces one shared secret with a mathematically linked key pair — a public half anyone can have and a private half only you hold — so two strangers can end up communicating securely without ever exchanging a secret in advance, at the cost of being far too slow for bulk data.

Public-key cryptography: the two-key trick

The last lesson ended at a wall: symmetric encryption needs both sides to already share a secret key, and there's no safe way to just send that key over the same network an attacker is watching. Public-key cryptography is the way around the wall — not by finding a clever way to hide a key in transit, but by inventing a kind of key that doesn't need to be hidden at all. Half of it is meant to be published. This lesson is about how that's mathematically possible, what it's actually used for, and why — despite solving the hardest problem in the whole module — it's still not what encrypts your data day to day.

The frame: a key pair — public and private, linked by a one-way mathematical relationship — lets a stranger encrypt something only you can open, or lets you sign something anyone can verify came from you, and both uses rest on math that's easy in one direction and computationally infeasible to reverse without the private half.

A pair, not a secret

Symmetric crypto has one key that does both jobs, and whoever has it can encrypt and decrypt. Public-key crypto splits that into two mathematically related keys: a public key, which you hand out to literally anyone — post it on your website, put it in a directory, it doesn't matter who sees it — and a private key, which you generate alongside it and never let leave your possession. They're linked so that whatever one of them does, only the other can undo. Encrypt with the public key, and only the matching private key decrypts it. That's the entire trick that solves the key-distribution problem: there's no secret to transmit, because half the pair was never secret to begin with.

The trapdoor: easy one way, infeasible the other

None of this works without a specific kind of math: a function that's cheap to compute in one direction and computationally infeasible to reverse unless you hold one extra piece of information — the private key. This is called a trapdoor function, and the two dominant ones are built on two different hard problems.

RSA rests on integer factoring. Multiply two large prime numbers together, and you get their product almost instantly — that's the easy direction, and it's what generates the public key. Given only that product, working backward to recover the two original primes is the hard direction: for numbers large enough (RSA keys today run 2048 to 4096 bits), no known algorithm on any existing computer can factor them in a useful amount of time. The private key is built from those primes; the public key is built from their product. Knowing the product doesn't get you the primes back.

ECC (elliptic-curve cryptography) rests on the elliptic-curve discrete logarithm problem. Points on a specially chosen curve can be "added" to each other under a defined operation; doing that addition repeatedly (scalar multiplication) is cheap, but given the starting point and the ending point, recovering how many times the addition was applied is computationally infeasible. That's the private key (the number of times) and the public key (the resulting point).

The practical payoff of ECC is size: a 256-bit ECC key gives roughly the same security as a 3072-bit RSA key. Smaller keys mean smaller handshake messages, less computation per operation, and less data to move — which is why ECC (specifically curves like P-256 and Curve25519) has become the preferred choice in modern protocols, including most of the web's TLS traffic, even though RSA is still everywhere in older systems and certificates.

Two directions, two different jobs

The key pair gets used in two distinct ways, and it's worth keeping them separate because they run in opposite directions.

Encryption for confidentiality: encrypt with the recipient's public key. Anyone can do this — the public key is, well, public — but only the matching private key can decrypt the result, so only the intended recipient can ever read it. This is how you achieve confidentiality with someone you've never shared a secret with: you don't need one, you just need their public key, which they can hand out openly.

Signatures for authenticity: operate with your own private key on a message (in practice, on a hash of the message), producing a signature. Anyone holding your public key can verify that signature was produced by your private key and that the message hasn't changed since. Only you could have produced it — nobody else has your private key — so a valid signature is proof of origin. This is the flip side of encryption: instead of "only one person can read this," it's "only one person could have produced this, and everyone can check." Signatures get the full mechanical treatment in lesson 6; for now, the important thing is which key does which job, and that it's the opposite pairing from encryption.

Why it's slow, and why that's fine

RSA and elliptic-curve operations involve arithmetic on numbers hundreds or thousands of bits long — modular exponentiation for RSA, repeated point addition for ECC. That's orders of magnitude more computation per operation than AES's simple substitution-and-shuffle on 128-bit blocks, which is why public-key operations run roughly a thousand times slower than symmetric ones, and why you essentially never use public-key crypto to encrypt the actual bulk of a message, a file, or a video stream directly.

Hybrid encryption is the pattern that makes this practical: use public-key crypto exactly once, to either directly encrypt a fresh random symmetric key (RSA can do this — encrypt a 256-bit AES key with the recipient's public key) or to jointly derive one (the key-exchange approach covered in lesson 7, which most modern protocols actually prefer, because it additionally provides forward secrecy). Either way, the expensive asymmetric math touches only a few hundred bytes — a key — once per connection, and the actual data, however large, flows through fast symmetric AEAD. This is exactly what happens when you load an HTTPS page: the TLS handshake uses public-key operations to authenticate the server and establish a shared secret, and every byte of the actual page content after that is symmetric.

// Generating an ECDH key pair with the Web Crypto API,
// for establishing a shared secret (hybrid-encryption style)
const keyPair = await crypto.subtle.generateKey(
  { name: "ECDH", namedCurve: "P-256" },
  true,
  ["deriveKey"]
);

// keyPair.publicKey can be exported and sent to anyone;
// keyPair.privateKey never leaves this side.
const exportedPublicKey = await crypto.subtle.exportKey(
  "raw",
  keyPair.publicKey
);

// Conceptually, once you also hold the other party's public key:
// const sharedAesKey = await crypto.subtle.deriveKey(
//   { name: "ECDH", public: theirPublicKey },
//   keyPair.privateKey,
//   { name: "AES-GCM", length: 256 },
//   false,
//   ["encrypt", "decrypt"]
// );
// That derived AES key is what actually encrypts the data —
// lesson 7 covers exactly how both sides land on the same value.

A brief note on the future: quantum computers

The hardness of both factoring and elliptic-curve discrete logarithms is a classical-computer assumption. A sufficiently large, fault-tolerant quantum computer running Shor's algorithm could solve both problems efficiently, which would break RSA and ECC as they're used today. That computer doesn't exist yet, and building one at the scale needed is still a hard open engineering problem — but "not yet" is why standards bodies are already rolling out post-quantum cryptography, new trapdoor problems (mostly lattice-based) believed to resist quantum attack, alongside the classical algorithms during the transition. It's a brief note here because it doesn't change anything about how you use RSA or ECC today, but it's worth knowing the two-key trick's math has a known theoretical expiration date, unlike the symmetric primitives from lesson 4.

Where this goes next

You now have both encryption families: symmetric for speed, public-key for solving the stranger problem — but signatures were only sketched here, as "the opposite of encryption." MACs and digital signatures gives that idea its full mechanical treatment: how a MAC authenticates with a shared key, how a signature authenticates with a key pair, and why "encrypted" and "authenticated" are still two separate guarantees even once you have both key types in hand.

Go deeper

  • MDN — SubtleCrypto.generateKey() Covers the exact parameters for generating RSA-OAEP, RSASSA-PKCS1, and ECDH/ECDSA key pairs in the browser's Web Crypto API.
  • Crypto 101 Builds up RSA and elliptic-curve math from first principles, including why factoring and discrete logarithms are believed to be hard.
  • Cloudflare — NIST's post-quantum cryptography standards A practical look at why RSA/ECC's security assumptions are being retired in favor of quantum-resistant algorithms, and on what timeline.

Check yourself

Answer out loud, as if an interviewer asked. If you hand-wave, reread that section.

  1. Why does having a mathematically linked key pair, instead of one shared key, solve the key-distribution problem symmetric encryption can't?
  2. What is a trapdoor function, and how does it differ for RSA (factoring) versus ECC (elliptic-curve discrete logarithm)?
  3. Why does a 256-bit ECC key offer roughly the same security as a 3072-bit RSA key, and why does that size difference matter in practice?
  4. For encryption, whose public key do you encrypt with and whose private key decrypts? For signing, which key operates first and which one verifies? Explain why these are opposite pairings.
  5. Why is public-key cryptography too slow to bulk-encrypt data directly, and what does 'hybrid encryption' do instead?
  6. How does the TLS handshake illustrate hybrid encryption — which parts use public-key operations and which part switches to symmetric AEAD?
  7. In one sentence, why do quantum computers threaten RSA and ECC specifically, and what's the field's response called?