Public-key cryptography, explained without the maths degree
Two keys are better than one — here is why the internet runs on asymmetric crypto.
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.
Encrypting (locking) and decrypting (opening) use different keys. You can share the locking key with the whole world without ever revealing the opening key.
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.
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.
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).
Intermediate
Let us look at each operation in turn, then see how real protocols stitch them together.
Symmetric vs asymmetric — a quick comparison
| Property | Symmetric (e.g. AES) | Asymmetric (e.g. RSA, ECC) |
|---|---|---|
| Keys | One shared secret key | A public/private key pair |
| Speed | Very fast — hardware-accelerated | Much slower — CPU-intensive maths |
| Key distribution | Must be shared securely in advance | Public key can be shared openly |
| Key length for ~128-bit security | 128 bits (AES-128) | 3072-bit RSA or 256-bit ECC |
| Typical use | Bulk data encryption | Key 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.
- 1Messageoriginal data
- 2SHA-256 hash32-byte digest
- 3Sign with private keyproduces signature
- 4Transmit message + signature
- 5Recipient hashes messageindependently
- 6Verify signature with public keydigests must match
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:
- Generate a random session key (a symmetric key, e.g. 256 bits of AES key material).
- Encrypt the session key with the recipient's public key (small, fast enough).
- Encrypt all payload data with the session key using AES-GCM or ChaCha20-Poly1305.
- The recipient decrypts the session key with their private key, then decrypts the payload.
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.
The network sees both public values but cannot compute the shared secret without knowing either private exponent — that is the discrete logarithm problem.
Advanced
RSA vs ECC
| Property | RSA | ECC |
|---|---|---|
| Hard problem | Integer factorisation | Elliptic-curve discrete logarithm |
| 128-bit-equivalent key | 3072 bits | 256 bits (e.g. P-256 or Curve25519) |
| Performance | Slower, especially key generation | Significantly faster; lower CPU cost |
| Signature size | Large (same size as key) | Much smaller |
| Common curves | N/A | P-256, P-384, Curve25519, secp256k1 |
| Common uses | Legacy TLS, older PKI, JWTs (RS256) | Modern TLS (ECDSA), SSH keys (Ed25519), code signing |
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.
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 signing —
git commit -Sattaches a GPG or SSH signature to the commit object;git log --show-signatureverifies it. - JWT signing —
RS256(RSA) orES256(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.
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 100use 100 rounds of bcrypt for the passphrase KDF. OpenSSL private keys useAES-256-CBCby 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:
AuthorizedKeysFileor anAuthorizedKeysCommandthat 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.
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:
- Inventory all systems using RSA or ECC for key exchange or signatures — TLS endpoints, SSH servers, code-signing pipelines, JWTs.
- Prioritise enabling forward secrecy (ECDHE) everywhere today — it limits the value of harvest-now attacks regardless of future quantum capability.
- Track OS/library PQC support: OpenSSL 3.x, Go, and the major cloud providers already offer hybrid or pure PQC options.
- 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.
- 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
| Symptom | Likely cause | Fix |
|---|---|---|
Permission denied (publickey) | Agent not running, wrong key presented, or key not in authorized_keys | ssh-add -l; check ~/.ssh/authorized_keys permissions (600) |
TLS: CERTIFICATE_VERIFY_FAILED | Missing intermediate CA, expired cert, or wrong hostname | Check openssl s_client -connect host:443 -showcerts chain |
| Signature verification failure | Message modified, wrong public key, or encoding mismatch (PEM vs DER) | Verify against the signer's correct public key; check encoding |
SSL_ERROR_NO_CYPHER_OVERLAP | Cipher suite or TLS version mismatch | Audit server config; ensure TLS 1.2+ and ECDHE suites are enabled |
JWT invalid signature | Wrong public key, alg confusion (alg:none), or payload tampered | Pin 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.
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