← All concepts
Security

Public-key cryptography, explained without the maths degree

Two keys are better than one — here is why the internet runs on asymmetric crypto.

15 min read · updated 20 Jun 2026
This concept is explained in five layers — from a simple analogy up to a deep technical dive. Read top-to-bottom, or jump to your level.
On this page
Level 1·A magic padlock that anyone can lock but only you can open.

Explain like I'm 5

Imagine you made a special padlock. You hand out thousands of copies of that padlock — open and unlocked — to everyone in the world. You keep the one key that closes and opens it.

If your friend wants to send you a secret message, they put it in a box and snap your padlock shut. Now nobody can open it — not even your friend — except you, because only you have the key.

That padlock is your public key. The key in your pocket is your private key. The maths that makes such a magical padlock possible is called public-key cryptography.

The big idea

Encrypting (locking) and decrypting (opening) use different keys. You can share the locking key with the whole world without ever revealing the opening key.

Level 2·Key pairs, what they solve, and the two things you can do with them.

Beginner

Before public-key cryptography existed, every pair of people who wanted to communicate privately needed to share the same secret key in advance — and share it safely, without anyone eavesdropping. With millions of users on the internet, that is an impossible logistics problem.

The key-distribution problem

Symmetric encryption is fast and strong, but it cannot bootstrap a secure channel by itself: you need a secure channel to share the key, which is the very thing you are trying to create.

Public-key (asymmetric) cryptography solves this by giving everyone a key pair: a public key you share freely, and a private key you never reveal.

The pair has two distinct uses:

  • Confidentiality — Anyone who wants to send you a secret message encrypts it with your public key. Only your private key can decrypt it.
  • Authenticity / integrity — You sign data with your private key. Anyone who has your public key can verify the signature and know the data came from you and has not been altered.
Remember which way round

Encrypt with public, decrypt with private. Sign with private, verify with public. Mix those up and nothing works.

Common algorithms you will meet: RSA (the classic choice, based on the difficulty of factoring large numbers) and ECC (elliptic-curve cryptography, which achieves the same strength with much smaller keys).

Level 3·How encryption, signing, hybrid crypto, and key exchange actually work.

Intermediate

Let us look at each operation in turn, then see how real protocols stitch them together.

Symmetric vs asymmetric — a quick comparison

PropertySymmetric (e.g. AES)Asymmetric (e.g. RSA, ECC)
KeysOne shared secret keyA public/private key pair
SpeedVery fast — hardware-acceleratedMuch slower — CPU-intensive maths
Key distributionMust be shared securely in advancePublic key can be shared openly
Key length for ~128-bit security128 bits (AES-128)3072-bit RSA or 256-bit ECC
Typical useBulk data encryptionKey exchange, signatures, certificates

Digital signatures sign a hash, not the raw message

Signing a large document directly with RSA or ECC arithmetic would be impractically slow. Instead, the signer first runs the message through a cryptographic hash function (e.g. SHA-256) to produce a short, fixed-length digest, then signs the digest. The verifier hashes the received message independently and checks the signature against that hash.

  1. 1
    Message
    original data
  2. 2
    SHA-256 hash
    32-byte digest
  3. 3
    Sign with private key
    produces signature
  4. 4
    Transmit message + signature
  5. 5
    Recipient hashes message
    independently
  6. 6
    Verify signature with public key
    digests must match
Sign and verify flow

Hybrid encryption — why real systems combine both

Because asymmetric operations are slow, real protocols never use them to encrypt bulk data. Instead they use hybrid encryption:

  1. Generate a random session key (a symmetric key, e.g. 256 bits of AES key material).
  2. Encrypt the session key with the recipient's public key (small, fast enough).
  3. Encrypt all payload data with the session key using AES-GCM or ChaCha20-Poly1305.
  4. The recipient decrypts the session key with their private key, then decrypts the payload.
You see this everywhere

TLS, PGP, SSH file transfer, and age all use hybrid encryption. The asymmetric step is just a secure envelope for the fast symmetric key.

Diffie-Hellman key exchange

Sometimes you do not want to encrypt a session key with a static public key — you want both sides to agree on a shared secret without either one choosing it unilaterally. That is Diffie-Hellman (DH). Both parties contribute randomness; an eavesdropper who sees all the messages cannot reconstruct the secret.

AliceNetwork (public)BobSends public value A(g^a mod p)Forwards A's valueSends public value B(g^b mod p)Forwards B's valueComputes shared secret B^a mod pComputes same secret A^b mod p
Diffie-Hellman key agreement (conceptual)

The network sees both public values but cannot compute the shared secret without knowing either private exponent — that is the discrete logarithm problem.

Level 4·RSA vs ECC, certificates and PKI, forward secrecy, and real-world deployments.

Advanced

RSA vs ECC

PropertyRSAECC
Hard problemInteger factorisationElliptic-curve discrete logarithm
128-bit-equivalent key3072 bits256 bits (e.g. P-256 or Curve25519)
PerformanceSlower, especially key generationSignificantly faster; lower CPU cost
Signature sizeLarge (same size as key)Much smaller
Common curvesN/AP-256, P-384, Curve25519, secp256k1
Common usesLegacy TLS, older PKI, JWTs (RS256)Modern TLS (ECDSA), SSH keys (Ed25519), code signing
New key? Reach for Ed25519

For SSH keys and code signing today, Ed25519 (EdDSA on Curve25519) is the recommended default: small keys, fast signing, strong security margin, and no reliance on a random-number generator for signing safety (unlike ECDSA).

Certificates and PKI — binding a public key to an identity

A bare public key tells you nothing about who owns it. A certificate is a digitally signed document that binds a public key to a name (domain, person, or organisation). The signature comes from a Certificate Authority (CA) whose own public key you already trust.

This chain of trust is the Public Key Infrastructure (PKI). Your browser ships with about 150 trusted root CAs; every TLS certificate on the web chains up to one of them. For a deep walkthrough of how TLS uses all this during connection setup, see the TLS handshake article.

Forward secrecy via ephemeral Diffie-Hellman (ECDHE)

In classic RSA key exchange, the server's long-lived private key is used to decrypt each session key. If that private key is later compromised, an adversary who recorded past traffic can decrypt it all retroactively.

Ephemeral Diffie-Hellman eliminates this. Both sides generate a fresh DH key pair for each session; the shared secret is derived through DH and neither side's long-term key can decrypt it later. TLS 1.3 mandates ECDHE — static RSA key exchange is gone.

No forward secrecy? No good.

Any TLS server still offering TLS_RSA_* cipher suites (no ephemeral DH) is vulnerable to retrospective decryption. Audit with openssl s_client or testssl.sh and disable those suites.

Real-world uses across infrastructure

  • TLS — ECDHE for key agreement, ECDSA or RSA certificate for server authentication, AES-GCM for data.
  • SSH — Ed25519 or RSA key pair authenticates the user; the server is authenticated by its host key (checked against ~/.ssh/known_hosts).
  • Signed packages/software — RPM, DEB, and container image manifests carry signatures; your package manager verifies them before install.
  • Git commit signinggit commit -S attaches a GPG or SSH signature to the commit object; git log --show-signature verifies it.
  • JWT signingRS256 (RSA) or ES256 (ECDSA) JWTs let a verifier check token authenticity using only the issuer's public key.
  • Kerberos PKINIT — smart-card and certificate-based Kerberos initial authentication uses the client's certificate private key in place of a password; see the Kerberos article.
Level 5·Key management, quantum threats, PQC migration, and troubleshooting.

Deep dive

Protecting and managing private keys

The private key is the crown jewel. If it is compromised, an attacker can impersonate you, decrypt historical traffic (if forward secrecy is not in use), and forge signatures. Treat it accordingly:

  • Passphrase-protect private keys at rest. SSH keys encrypted with ssh-keygen -a 100 use 100 rounds of bcrypt for the passphrase KDF. OpenSSL private keys use AES-256-CBC by default.
  • Use an ssh-agent or GPG agent so the passphrase is entered once per session and the raw key material stays in memory, not on disk repeatedly.
  • Hardware security modules (HSMs) and security keys (YubiKey, etc.) store the private key in tamper-resistant hardware; signing operations happen inside the device — the key never leaves.
  • Rotate keys proactively, not just after suspected compromise. TLS certificates have explicit expiry; SSH host keys and code-signing keys should have a documented rotation policy.
  • Revocation — for TLS: CRL or OCSP stapling. For PGP: upload a revocation certificate to keyservers before you lose access. For SSH: AuthorizedKeysFile or an AuthorizedKeysCommand that centralises trust.

The quantum threat

Shor's algorithm, running on a sufficiently powerful quantum computer, can solve integer factorisation (breaks RSA) and the discrete logarithm problem (breaks DH, DSA, and ECC) in polynomial time. A cryptographically relevant quantum computer does not yet exist, but nation-state adversaries are almost certainly conducting harvest-now, decrypt-later attacks — recording encrypted traffic today to decrypt once a quantum computer is available.

Harvest-now, decrypt-later is already happening

Data encrypted today with RSA or ECC key exchange — without forward secrecy — could be decrypted in a post-quantum future. Long-lived secrets (e.g. government, medical, financial records) are at highest risk.

Post-quantum cryptography (PQC)

NIST finalised its first PQC standards in 2024:

  • ML-KEM (formerly CRYSTALS-Kyber, FIPS 203) — lattice-based key encapsulation mechanism; replaces DH/ECDH for key agreement.
  • ML-DSA (formerly CRYSTALS-Dilithium, FIPS 204) — lattice-based digital signature; replaces RSA/ECDSA.
  • SLH-DSA (formerly SPHINCS+, FIPS 205) — hash-based signature scheme; conservative fallback with no lattice assumptions.

TLS 1.3 implementations are beginning to support X25519MLKEM768 hybrid key exchange, which combines classical ECDH with ML-KEM so that a classical or quantum attacker would need to break both. Chrome and Firefox already negotiate this with supporting servers.

Practical migration checklist:

  1. Inventory all systems using RSA or ECC for key exchange or signatures — TLS endpoints, SSH servers, code-signing pipelines, JWTs.
  2. Prioritise enabling forward secrecy (ECDHE) everywhere today — it limits the value of harvest-now attacks regardless of future quantum capability.
  3. Track OS/library PQC support: OpenSSL 3.x, Go, and the major cloud providers already offer hybrid or pure PQC options.
  4. Plan for larger key and signature sizes (ML-DSA signatures are ~2.4 kB vs ~64 bytes for Ed25519) — review MTU, certificate chain size limits, and any fixed-size buffers.
  5. Benchmark ML-KEM and ML-DSA on your hardware; performance is generally acceptable but may surprise you on constrained devices.

Troubleshooting common public-key problems

SymptomLikely causeFix
Permission denied (publickey)Agent not running, wrong key presented, or key not in authorized_keysssh-add -l; check ~/.ssh/authorized_keys permissions (600)
TLS: CERTIFICATE_VERIFY_FAILEDMissing intermediate CA, expired cert, or wrong hostnameCheck openssl s_client -connect host:443 -showcerts chain
Signature verification failureMessage modified, wrong public key, or encoding mismatch (PEM vs DER)Verify against the signer's correct public key; check encoding
SSL_ERROR_NO_CYPHER_OVERLAPCipher suite or TLS version mismatchAudit server config; ensure TLS 1.2+ and ECDHE suites are enabled
JWT invalid signatureWrong public key, alg confusion (alg:none), or payload tamperedPin the expected algorithm in your verifier; never accept alg:none

A useful sanity-check tool when debugging hash or signature problems is the hash generator, which lets you compute SHA-256 and other digests interactively.

ApplicationsTLS, SSH, JWT, signed packages, Git signing
ProtocolsX.509 / PKI | ECDHE key exchange | PQC hybrids
PrimitivesRSA | ECDSA / Ed25519 | DH / ECDH | ML-KEM / ML-DSA
Hard maths problemsInteger factorisation | Discrete logarithm | Lattice problems
Public-key cryptography system overview
The one-paragraph summary

Public-key cryptography solves the key-distribution problem by giving each party a mathematically linked key pair: the public key encrypts or verifies; the private key decrypts or signs. Because asymmetric operations are slow, real systems use hybrid encryption — asymmetric crypto to exchange a fast symmetric session key. Digital signatures sign a hash of the message, providing authenticity and integrity. Ephemeral Diffie-Hellman (ECDHE) adds forward secrecy so past sessions stay safe even if a long-term key is later stolen. Modern deployments favour ECC (Ed25519, P-256) over RSA for smaller keys and better performance. The coming quantum threat means RSA and ECC key exchange have a finite shelf life — start auditing for forward secrecy now and watch NIST's PQC standards (ML-KEM, ML-DSA) for your migration path.

Frequently asked questions

What is the difference between public-key and symmetric encryption?

Symmetric encryption uses one shared secret key for both encryption and decryption — it is fast but requires the two parties to exchange that key securely first. Public-key (asymmetric) encryption uses a mathematically linked key pair so the encryption key can be shared openly. In practice, the two are combined: asymmetric crypto exchanges a symmetric session key, then symmetric crypto encrypts the actual data.

Can someone decrypt my data if they have my public key?

No. The public key can only encrypt data (or verify signatures). Decryption requires the corresponding private key. Sharing your public key freely is not only safe — it is the whole point.

What is a digital signature and how does it prove authenticity?

The sender hashes the message with a function such as SHA-256, then encrypts that hash with their private key to produce a signature. Anyone with the sender's public key can decrypt the signature, independently hash the received message, and check the two hashes match. If they match, the message came from the private-key holder and has not been altered.

Is RSA broken by quantum computers?

Not yet, but Shor's algorithm running on a sufficiently powerful quantum computer would break RSA and ECC in polynomial time. Such machines do not exist today, but 'harvest now, decrypt later' attacks mean data encrypted without forward secrecy is at risk. NIST's post-quantum standards (ML-KEM, ML-DSA) are the migration target.

What is forward secrecy and why does it matter?

Forward secrecy means that each session uses a freshly generated ephemeral key pair for key exchange (ECDHE in TLS 1.3). Even if a server's long-term private key is later stolen, an attacker cannot retroactively decrypt recorded sessions because the ephemeral keys were never persisted.

Should I use RSA or Ed25519 for new SSH keys?

Ed25519 for new keys, without hesitation. It is faster, produces smaller keys and signatures, has a strong security margin, and does not depend on the quality of the random number generator at signing time (unlike ECDSA). Use RSA-4096 only where a system explicitly does not support Ed25519.

ShellQuest turns concepts like this into bite-sized lessons, puzzles and labs you actually practise.

Join the waitlist