Five building blocks cover almost everything in PKI. Learn what each one promises, and just as important, what it does not promise.
| Building block | Promises | Does not promise |
|---|---|---|
| Hash | Integrity: any change is detectable | Secrecy, or who made it |
| MAC / HMAC | Integrity and authenticity, to someone who shares the key | Proof to a third party (both sides can make it) |
| Symmetric encryption | Confidentiality, fast | Safe key distribution |
| Public-key encryption / key exchange | Agree on a secret with a stranger | Who the stranger is |
| Digital signature | Integrity, authenticity, non-repudiation | Confidentiality |
Random numbers
Every key, token and password-reset link starts life as a random number. The whole security of a key rests on one fact: an attacker cannot predict it. The length of the key does not matter if the way it was made is guessable. A “256-bit” key built from the current time in seconds has only a few dozen bits of real unpredictability, because there are only so many seconds in a year for an attacker to try.
That is a problem, because a computer is a deterministic machine: given the
same starting state it does exactly the same thing every time. It cannot
produce randomness by itself. So the operating system collects unpredictable
events (tiny timing differences in disk and network activity, hardware random
number generators in the CPU, and so on). This is called entropy. It then
feeds them into a CSPRNG (cryptographically secure pseudo-random number
generator), which stretches a small amount of entropy into as many random
bytes as you ask for. On Linux and macOS this is /dev/urandom (or the
getrandom() system call), and OpenSSL uses it for you.
What “never invent your own” means in practice:
- Do not use ordinary random functions such as
rand(),Math.random()or Python’srandommodule for secrets. They are fast and statistically random-looking, but predictable. Usesecrets(Python),crypto.randomBytes(Node),crypto/rand(Go), oropenssl rand. - Do not turn a memorable phrase into a key by hand-rolling something such as “hash my company name twice”. Humans are very bad at being random, and attackers try human patterns first.
- Do not write your own algorithm and do not tweak a standard one. The standard ones survived years of attack by professionals; yours has not.
Real incidents show why this matters. In 2008 it was found that a change to Debian’s OpenSSL package had accidentally crippled the random number generator. For about two years every key it made came from one of only about 32,000 possibilities, so attackers could simply list them all. In 2012 researchers scanned the internet and found thousands of RSA keys that shared a prime number with another device’s key, which makes both keys easy to break. Most came from small embedded devices that generated their keys at first boot, before they had gathered any entropy.
$ openssl rand -hex 16
9ea814481f14a87f6575b068ad608908
$ openssl rand -base64 32
vwoUakj9UTwyKfFUcQgHplgiJjvShTM7XhvAPFFIA8M=
The first command printed 16 random bytes (128 bits) as 32 hex characters, a good size for a key or a session ID. The second printed 32 bytes (256 bits), encoded as base64 so it is printable. Run the commands again and you get different values every time: that is the point.
Hashes
A hash function reads any amount of data, a word or a 4 GB disk image, and produces a short, fixed-size fingerprint (the digest). SHA-256 always gives 256 bits, shown as 64 hex characters. Three properties make it useful:
- Deterministic. The same input always gives the same fingerprint, on any computer. That is what lets two people compare a 4 GB download by comparing 64 characters.
- One-way. You cannot work backwards from the fingerprint to the input. There are infinitely many possible inputs and only 2²⁵⁶ possible outputs, so a fingerprint does not even contain enough information to rebuild the original. This is why a hash is not encryption: there is nothing to decrypt.
- Avalanche effect. Change one character and about half of the output bits flip. You cannot “get close” to a target fingerprint by making small edits, which is what makes tampering detectable.
A good hash is also collision resistant: nobody can find two different inputs that give the same fingerprint. This is the property that failed for old hashes (see below).
$ echo "hello world" > msg.txt
$ openssl dgst -sha256 msg.txt
SHA2-256(msg.txt)= a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447
$ echo "hello world!" | openssl dgst -sha256
SHA2-256(stdin)= ecf701f727d9e2d77c4aa49ac6fbbcc997278aca010bddeeb961c10cf54d435a
One added ! produced a completely different output. (The SHA2-256(...)=
text is just OpenSSL’s label; the 64 hex characters are the hash.)
Use SHA-256 or better (SHA-384, SHA-512, SHA3). MD5 and SHA-1 are broken for signatures. “Broken” here means collisions can be made on purpose: an attacker can build two different documents with the same fingerprint. That attack is not theoretical. In 2008 researchers used MD5 collisions to create a fake CA certificate that browsers would have trusted, and in 2017 Google published two different PDF files with the same SHA-1 hash. If a CA signs the hash of a harmless request, and the attacker holds a different, malicious document with the same hash, the signature is valid for both.
Where you will meet hashes:
- Certificate fingerprints: the SHA-256 of the certificate, used to confirm “this is the certificate I meant” (for example when installing a root CA).
- File checksums: confirming a download was not corrupted or swapped.
- Digital signatures: a signature does not sign the whole document; it signs the document’s hash, which is small and fast to process.
- Password storage: only a hash is stored (but see the next section, a plain hash is not enough).
Passwords need a slow hash
Imagine a website’s user database leaks and it contains plain SHA-256 hashes of passwords. The attacker cannot reverse the hashes, but they do not need to: they hash millions of likely passwords (“password1”, “Summer2026!”) and look for matches. A modern graphics card can try billions of SHA-256 guesses per second, so any password a human would pick falls in minutes.
Password storage therefore uses a different kind of hash, designed to be slow on purpose, with two additions:
- A salt: a random value, unique per user, mixed into the hash and stored next to it. Two users with the same password then get different hashes, and the attacker cannot reuse one pre-computed table of guesses (“rainbow table”) against everyone.
- An iteration count (or memory cost): the function repeats its work many times so that each guess costs the attacker real time. A login that takes 50 ms is fine for you; multiplied by billions of guesses it is ruinous for them.
Use PBKDF2, scrypt or Argon2. (OWASP’s current guidance for PBKDF2 with SHA-256 is 600,000 iterations, which is the number below.)
$ openssl kdf -keylen 32 -kdfopt digest:SHA256 -kdfopt pass:secret \
-kdfopt salt:salt1234 -kdfopt iter:600000 PBKDF2
18:EE:9A:8C:26:72:1A:7F:77:CC:19:0B:E7:87:CB:E9:...
The output is a 32-byte key derived from the password. Give it the same
password, salt and iteration count and you get exactly the same bytes, which
is how a login check works: derive again and compare. The same trick turns a
human password into an encryption key, which you will see in a moment.
(Real systems generate a fresh random salt per user, rather than the
salt1234 used here for readability.)
HMAC: a hash with a secret key
A plain hash cannot protect a message in transit. If an attacker changes the message, they simply compute the new hash too, and nothing looks wrong. An HMAC (hash-based message authentication code) fixes this by mixing a secret key into the hash. Only someone who holds the key can produce the correct tag, so a matching tag tells the receiver two things: the message was not altered, and it came from someone who knows the key.
Where it is used: webhook signatures (the sender and your server share a
secret), JWTs signed with HS256, API request signing, and ACME’s External
Account Binding (see enrollment).
The limit: both sides hold the same key, so either could have produced a given tag. An HMAC cannot prove to a third party which of the two wrote the message. That stronger promise (“only Bob could have done this”, called non-repudiation) needs a digital signature, covered below.
$ openssl mac -digest SHA256 -macopt hexkey:$(openssl rand -hex 32) -in msg.txt HMAC
88592EC4D3686E38FF71B8402256CB4B07F34989605F2B8910AEC219FBE74C7A
Here a random 32-byte key was generated on the spot and used to tag
msg.txt. Without that key, no one can recompute the tag, and a receiver
who has the key recomputes it and compares. (Compare tags with a
constant-time function, which crypto libraries provide, not with a plain
==.)
Symmetric encryption
With symmetric encryption one secret key both locks and unlocks the data, like a house key that is used on the way in and the way out. AES is the standard cipher, with 128-bit or 256-bit keys, and it is extremely fast (modern CPUs have AES instructions built in). Both 128 and 256 bits are considered unbreakable by classical computers; 256 is chosen when a longer safety margin is wanted, including against future quantum attacks.
A cipher alone only transforms one small block (16 bytes for AES). The mode says how to apply it to a whole file, and the choice matters as much as the cipher:
- ECB encrypts every block independently, so identical blocks of input give identical blocks of output and patterns in the data stay visible (the famous “ECB penguin”: an encrypted picture that is still recognisable). Never use it.
- CBC and CTR hide patterns, but give no protection against tampering. An attacker can flip bits in the ciphertext and the receiver decrypts the altered result without any error.
- GCM (and ChaCha20-Poly1305) are authenticated modes: they add a tag that is checked on decryption, so any change to the ciphertext is detected and rejected. Use these in real software.
Each encryption also needs a fresh IV / nonce, a value that is unique per message. Reusing a nonce with the same key breaks GCM badly; libraries handle it for you, which is another reason not to build your own.
$ openssl enc -aes-256-cbc -pbkdf2 -iter 600000 -salt \
-in msg.txt -out msg.enc -pass pass:secret
$ xxd msg.enc | head -2
00000000: 5361 6c74 6564 5f5f d97b da4f 9c16 c780 Salted__.{.O....
$ openssl enc -d -aes-256-cbc -pbkdf2 -iter 600000 -in msg.enc -pass pass:secret
hello world
What happened: you gave OpenSSL a password, not a key. It picked a random
salt and ran the password through PBKDF2 (the slow hash from before) to
derive the real 256-bit AES key and IV. The file begins with the plain text
Salted__ followed by the salt, which is why the hexdump shows it: the salt
is not secret, it only has to be stored so decryption can rebuild the same
key. Because the salt is random, encrypting the same file twice gives
different output each time.
openssl enc cannot do authenticated modes such as GCM
(enc: AEAD ciphers not supported). It is a teaching tool. For real files
use age, GPG, or a library. Also, -pass pass:... puts the password in
your shell history and process list; use -pass stdin or file: instead.The problem: both sides need the same key, and it must reach the other side secretly. That is a chicken-and-egg problem. To send a secret key you first need a secure channel, and to have a secure channel you need a secret key. It also does not scale: a company of 1,000 people who each need a private channel with every other person would need almost 500,000 separate keys, each delivered securely.
Public-key cryptography solves both problems: two strangers can agree on a secret over a channel that an attacker is watching.
Public and private keys
A key pair has two mathematically linked halves:
- The private key is secret. Only the owner has it.
- The public key is shared with everyone.
What one key does, only the other can undo (or verify). It works because of maths that is easy in one direction and practically impossible in the other. Multiplying two huge prime numbers takes a computer a blink; factoring the result back into the two primes would take longer than the age of the universe. That is the idea behind RSA. Elliptic curves use a different one-way problem, covered below. The private key is the “secret shortcut” that makes the hard direction easy, and the public key is derived from it. You can always compute the public key from the private key, but never the other way round, so publishing it is safe.
Common algorithms:
| Algorithm | Typical size | Notes |
|---|---|---|
| RSA | 2048 minimum, 3072 better | Old, universal, big keys, slow to generate |
| ECDSA / ECDH (P-256, P-384) | 256, 384 bits | Small, fast, widely supported, FIPS-approved |
| Ed25519 / X25519 | 256 bits | Small, fast, hard to misuse. Not yet in FIPS 140-2 modules; allowed in FIPS 186-5 |
| ML-KEM, ML-DSA, SLH-DSA | larger | Post-quantum (see below) |
The padlock analogy
Picture a box and a padlock.
Encryption (keeping a secret). Bob makes a thousand identical open padlocks and hands them out to anyone: these are his public key. He keeps the one key that opens them: his private key.
- Alice wants to send Bob a secret. She puts it in a box and snaps one of Bob’s padlocks shut. She does not need to meet Bob or share a secret first.
- Anyone can see the box in transit, and anyone can have a padlock. But only Bob’s private key opens it.
- Bob opens the box.
Signing (proving who wrote it). This is the reverse. Bob has a personal wax seal that only he owns (private key), and a picture of the seal that everybody has (public key). He stamps a letter with the seal. Anyone can compare the stamp with the picture and know it came from Bob and was not altered, but nobody can forge the seal.
| In the story | In real life |
|---|---|
| Open padlock handed to everyone | Public key |
| Padlock key that stays with Bob | Private key |
| Snapping a padlock shut on a box | Encrypting with the recipient’s public key |
| Opening it with the key | Decrypting with the private key |
| Wax seal | Signing with the private key |
| Comparing the stamp to the published picture | Verifying with the public key |
So there are two different uses, and the keys are used in opposite directions:
| Goal | Who uses which key |
|---|---|
| Confidentiality (“only Bob can read this”) | Sender encrypts with Bob’s public key; Bob decrypts with his private key |
| Authenticity (“only Bob could have written this”) | Bob signs with his private key; anyone verifies with his public key |
The same story with OpenSSL
Bob creates his key pair, and publishes only the public half:
$ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out bob.key
$ openssl pkey -in bob.key -pubout -out bob.pub
Alice locks a message to Bob (needs only bob.pub):
$ echo "meet at noon" > secret.txt
$ openssl pkeyutl -encrypt -pubin -inkey bob.pub \
-pkeyopt rsa_padding_mode:oaep -in secret.txt -out secret.enc
secret.enc is unreadable noise. Bob unlocks it (needs bob.key):
$ openssl pkeyutl -decrypt -inkey bob.key \
-pkeyopt rsa_padding_mode:oaep -in secret.enc
meet at noon
Nobody else can do that last step, not even Alice. Now the wax seal: Bob signs, and Alice verifies:
$ openssl dgst -sha256 -sign bob.key -out secret.sig secret.txt
$ openssl dgst -sha256 -verify bob.pub -signature secret.sig secret.txt
Verified OK
Make keys
genpkey generates a private key (using the random number generator from the
start of this page), and pkey -pubout derives its public half. The -algorithm
and -pkeyopt choose the kind of key; the next section explains which to
pick.
$ openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out ec.key
$ cat ec.key
-----BEGIN PRIVATE KEY-----
MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgZDrkrokAtdbvKefe
/uN/c74LZCnAM6ZNM1++kLbLbRqhRANCAATSAll3FOEHmeSi35cwDGPgOsc5getw
9tbAhVoXKJq7vhDnU0yPiebdpjsizWMw8rRht0IAPEnd7KkHaRHX74NV
-----END PRIVATE KEY-----
$ openssl pkey -in ec.key -pubout -out ec.pub
$ cat ec.pub
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE0gJZdxThB5nkot+XMAxj4DrHOYHr
cPbWwIVaFyiau74Q51NMj4nm3aY7Is1jMPK0YbdCADxJ3eypB2kR1++DVQ==
-----END PUBLIC KEY-----
The -----BEGIN ...----- lines are the PEM format: the key’s binary data,
base64-encoded so it can be copied around as text (the
key formats page explains this
fully). The two blocks look similar, but they are very different in
sensitivity: ec.key must stay secret, and ec.pub can be pasted into an
email.
Look inside. The private key is a 32-byte number; the public key is a point
computed from it (04 means “uncompressed point”):
$ openssl pkey -in ec.key -text -noout
Private-Key: (256 bit field, 128 bit security level)
priv:
64:3a:e4:ae:89:00:b5:d6:ef:29:e7:de:fe:e3:7f:73:
be:0b:64:29:c0:33:a6:4d:33:5f:be:90:b6:cb:6d:1a
pub:
04:d2:02:59:77:14:e1:07:99:e4:a2:df:97:30:0c:63:
...
ASN1 OID: prime256v1
NIST CURVE: P-256
Other algorithms are the same command with a different -algorithm:
$ openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:3072 -out rsa.key
$ openssl genpkey -algorithm ED25519 -out ed.key
A private key file lying on disk is a risk: anyone who can read it can use it.
Two cheap protections are a passphrase (the file is encrypted with a key
derived from it, the same technique as before; note ENCRYPTED in the
header) and file permissions: 0600 means only the owning user can read
or write the file.
$ openssl pkey -in ec.key -aes-256-cbc -passout pass:changeit -out ec.enc.key
$ head -1 ec.enc.key
-----BEGIN ENCRYPTED PRIVATE KEY-----
$ chmod 600 *.key
RSA vs ECDSA: key sizes, curves and what to choose
How they differ
| RSA | ECDSA (elliptic curve) | |
|---|---|---|
| Hard problem | Factoring a huge number (n = p × q) | Finding k from the points P and k·P on a curve |
| The “size” you choose | Modulus length in bits: 2048, 3072, 4096 | A named curve: P-256, P-384, P-521 |
| Public key | A big number n plus exponent e | A point (x, y) on the curve |
| Signing | Slow | Fast |
| Verifying | Very fast | Slower than RSA |
| Key generation | Slow: searches for two large primes | Instant: pick a random number |
| Encryption | Yes (OAEP) | No: only signing and key exchange (ECDH) |
RSA and ECDSA are not variants of one idea; they rest on different maths. That is why their sizes cannot be compared directly.
What “key size” and “curve” mean for security
Security is measured in bits of security: breaking it should take about 2ⁿ operations. 128 bits is out of reach of any attacker today; 192 and 256 bits are extra margin. (Numbers below follow NIST SP 800-57.)
| Algorithm | Key | Security | Notes |
|---|---|---|---|
| RSA | 2048 | 112 bits | The minimum still acceptable. NIST disallows 112-bit security after 2030 |
| RSA | 3072 | 128 bits | The sensible RSA choice today |
| RSA | 4096 | ~140 bits | Not a NIST tier. A lot slower for a modest gain |
| ECDSA | P-256 | 128 bits | Same strength as RSA-3072 |
| ECDSA | P-384 | 192 bits | Same strength as RSA-7680 |
| ECDSA | P-521 | 256 bits | Rarely needed (and the number is 521, not 512) |
| EdDSA | Ed25519 | ~128 bits | Small, fast, hard to misuse |
Why is an EC key so much smaller for the same strength? The best known attack on RSA (the number field sieve) is much smarter than brute force, so RSA needs large numbers to stay safe. The best known attacks on a well-chosen elliptic curve are little better than brute force (about the square root of the group size), so a 256-bit curve gives 128 bits of security: EC security ≈ half the key size.
A curve is a set of agreed parameters
A curve fixes the equation, the prime field and the starting point, so two parties can do maths on the same curve. The names are confusing because standards bodies each named the same curve:
| Common name | Other names | Used for |
|---|---|---|
| P-256 | prime256v1, secp256r1 | TLS, most certificates, WebAuthn, hardware chips |
| P-384 | secp384r1 | CA keys, government and high-assurance use |
| P-521 | secp521r1 | Rare |
| secp256k1 | Bitcoin and Ethereum. Not the same as P-256 | |
| Curve25519 / Ed25519 | X25519 / EdDSA | SSH, modern TLS key exchange |
openssl ecparam -list_curves lists them; OpenSSL prints the common name
and the OID when you inspect a key (NIST CURVE: P-256, ASN1 OID: prime256v1).
A matching hash is used: P-256 with SHA-256, P-384 with SHA-384.
Measured on a laptop
Real numbers from openssl speed and the lab keys (Apple arm64, OpenSSL 4.1,
one thread; your machine will differ, but the ratios hold):
| Key | Public key (DER) | Signature | Sign / s | Verify / s | New keys / s |
|---|---|---|---|---|---|
| RSA 2048 | 294 B | 256 B | 1,818 | 70,910 | ~22 |
| RSA 3072 | 422 B | 384 B | 621 | 33,361 | ~7 |
| RSA 4096 | 550 B | 512 B | 288 | 19,328 | ~4 |
| ECDSA P-256 | 91 B | 72 B | 55,583 | 18,934 | instant |
| ECDSA P-384 | 120 B | 102 B | 6,988 | 3,305 | instant |
| ECDSA P-521 | 158 B | 137 B | 4,729 | 2,630 | instant |
| Ed25519 | 44 B | 64 B | 31,990 | 11,853 | instant |
What it shows:
- Going RSA 2048 → 4096 makes signing 6× slower and the signature 2× bigger.
- RSA-3072 and P-256 are the same strength, yet P-256 signs about 90× faster and its signature is 5× smaller.
- RSA wins only at verifying, which is why RSA is not “dead”: a device that mostly checks signatures does fine with it.
- P-384 is about 8× slower to sign than P-256 here. That is still thousands of signatures a second, which a CA, or a normal server, will never miss.
Size matters in the real world: every TLS handshake carries certificates and signatures. Smaller keys mean faster handshakes, less bandwidth, and fit on constrained devices, QR codes and smart cards.
Which should you use?
| Situation | Recommendation | Why |
|---|---|---|
| Servers, devices, workloads, users (end-entity certificates) | ECDSA P-256 | 128-bit security, smallest, fastest, supported everywhere. The default for most new keys |
| CA keys (root and intermediate) | ECDSA P-384 | A CA key lives for years and signs many things, so it deserves the extra margin (192 bits). The speed cost is paid rarely |
| Compliance (US government, CNSA 1.0, many contracts) | P-384 or RSA 3072+ | Required or expected by those profiles |
| Legacy or restricted systems that only do RSA | RSA 3072 (2048 only if you must) | Maximum compatibility. 2048 is the floor, and it ages out by 2030 |
| SSH keys | Ed25519 | Simple and safe. See SSH certificates |
This is why the tutorial’s own lab uses a P-384 root, a P-256 intermediate and P-256 leaf keys: the long-lived key gets the most margin, and the high-volume keys stay cheap.
Why not the others?
- Why not RSA 4096 “to be safe”? It is 6× slower to sign than RSA-2048, makes bigger certificates, and adds only a little security (about 140 bits). If you want more than 128 bits, P-384 gives 192 for a smaller and faster key. RSA 4096 is still common for long-lived roots because it is universally supported, and that is a fine reason, but not a security one.
- Why not RSA 2048? It is the floor, not a target: 112 bits, and NIST stops accepting it after 2030. Fine for existing systems, but do not start new long-lived keys with it.
- Why not P-384 everywhere? It costs more CPU, bytes and battery for security you do not need at the leaf. A 90-day leaf certificate does not need a 192-bit key. Also, some hardware only supports P-256 (many TPMs and the Apple Secure Enclave), so insisting on P-384 can make device attestation impossible.
- Why not P-521? Slower again, rarely supported by hardware and clients, and there is no practical benefit over P-384.
- Why not Ed25519 for certificates? It is excellent, but support is thin in public WebPKI rules (the CA/Browser Forum allows RSA and ECDSA P-256, P-384 and P-521 for public TLS), HSMs and FIPS-validated modules. Use it where you control both ends, such as SSH.
- Why not just use bigger keys forever? Because of quantum computers. A large quantum computer breaks RSA and elliptic curves with Shor’s algorithm, regardless of size. Larger keys only buy time against classical attackers. The real answer is the move to post-quantum algorithms.
Weak spots to know
| Pitfall | Defence | |
|---|---|---|
| ECDSA | Every signature needs a fresh, unpredictable nonce. A repeated or biased nonce leaks the private key (this broke the PlayStation 3’s signing key) | Good RNG, deterministic nonces (RFC 6979), or sign inside an HSM. Ed25519 avoids this by design |
| RSA | Wrong padding is a classic breakage (PKCS#1 v1.5) | Use PSS for signing and OAEP for encryption |
| RSA | Weak random numbers at key generation produced real keys that share a prime and can be factored | Generate on a machine with good entropy. Never from a freshly booted embedded device image |
| RSA | Keys under 2048 bits | Do not |
| NIST curves | Some people distrust the unexplained constants behind P-256/P-384. No weakness is known and they are used by governments and banks | If you want to avoid them, use Curve25519 and accept thinner hardware and FIPS support |
Digital signatures
Sign with the private key; anyone verifies with the public key.
How it works: the signer first computes the hash of the message, then uses the private key to transform that hash into a signature (a short blob of bytes). A verifier computes the hash of the message they received and uses the public key to check that the signature really is a valid signature of that hash. If one byte of the message changed, the hash changes, and the check fails. If someone without the private key tried to make a signature, they could not.
$ openssl dgst -sha256 -sign ec.key -out msg.sig msg.txt
$ openssl dgst -sha256 -verify ec.pub -signature msg.sig msg.txt
Verified OK
$ echo tampered > msg2.txt
$ openssl dgst -sha256 -verify ec.pub -signature msg.sig msg2.txt
Verification failure
The second check failed because msg2.txt is not the message that was signed.
A failure only tells you “this signature does not match this message under
this key”. It does not say why (altered message, wrong key, corrupted
signature), which is a useful thing to remember when debugging.
A signature gives you three things: integrity (the data is unchanged), authenticity (it was signed by the holder of the private key) and non-repudiation (the signer cannot later deny it, since nobody else has that key, unlike an HMAC). What it does not tell you is who owns the key. A signature proves “someone with this private key signed this”. Linking the key to a real name is the job of a certificate.
This is the single most important idea in PKI: a certificate is just a public key plus a name, signed by a CA. If you can verify the CA’s signature, you can trust the name-to-key binding.
Encrypting with a public key, and key exchange
RSA can encrypt a small secret to someone’s public key (always with OAEP padding, never PKCS#1 v1.5):
$ openssl pkeyutl -encrypt -pubin -inkey r2.pub -pkeyopt rsa_padding_mode:oaep \
-in msg.txt -out msg.rsa
$ openssl pkeyutl -decrypt -inkey r2.key -pkeyopt rsa_padding_mode:oaep -in msg.rsa
hello world
Modern protocols (TLS 1.3, SSH) instead use Diffie-Hellman key exchange. The classic way to picture it is mixing paint. Alice and Bob publicly agree on a yellow paint. Each secretly picks a private colour (Alice red, Bob blue), mixes it into the yellow and sends the mixture to the other. An eavesdropper sees both mixtures, but cannot un-mix paint. Alice then adds her secret red to the mixture she got from Bob, and Bob adds his secret blue to the mixture from Alice. Both end up with yellow + red + blue, the same colour, and the colour itself never travelled.
In real cryptography, “mixing” is elliptic-curve maths: each side combines its own private key with the other’s public key, and both arrive at the same secret, which is never sent:
$ openssl pkeyutl -derive -inkey ec.key -peerkey b.pub | xxd -p -c 64
61aeeec6e9e45ed23f7d7b000d3df21f3aa7b27ba4430f8f4b6a353207208372
$ openssl pkeyutl -derive -inkey b.key -peerkey ec.pub | xxd -p -c 64
61aeeec6e9e45ed23f7d7b000d3df21f3aa7b27ba4430f8f4b6a353207208372
The two commands used different key pairs (ec.key with b.pub, then b.key
with ec.pub) and printed the same 32 bytes. That shared value is then
fed through a key-derivation function to make the AES keys for the session.
Using fresh (ephemeral) keys for every connection gives forward secrecy. Imagine an attacker who records all encrypted traffic for a year and, later, steals the server’s long-term private key. If the session keys had been derived from that long-term key, they could decrypt everything. With ephemeral key exchange the session secrets were made from throw-away keys that were deleted after the connection, so the stolen key decrypts nothing from the past. In TLS 1.3 this is always on.
Putting it together: hybrid encryption
Each tool has a weakness: symmetric encryption is fast but needs a shared key; public-key operations solve the sharing but are slow and can only handle small messages. Real systems use each for what it does best:
- Use key exchange (or RSA) to agree on a random symmetric key. This is the one small, slow step.
- Encrypt the actual data with AES-GCM using that key. This is fast, and handles gigabytes.
- Sign something with a private key (and show a certificate) to prove who you are, so that you are not agreeing a secret with an impostor.
TLS, SSH, S/MIME email and disk-encryption key wrapping all follow this pattern. When you open an HTTPS page, steps 1 to 3 happen in a fraction of a second, before the first byte of the page is sent. The next page, How HTTPS works, follows these three steps through real TLS 1.3 and TLS 1.2 handshakes, including why RSA and ECDSA only sign.
Post-quantum cryptography
A large quantum computer could run Shor’s algorithm, which solves the factoring and elliptic-curve problems efficiently. That would break RSA, ECDSA and Diffie-Hellman at any key size; making keys bigger does not help. Such a machine does not exist yet, but the risk is already real for data that must stay secret for decades: an attacker can record encrypted traffic today and decrypt it once the machine exists ("harvest now, decrypt later").
The good news: symmetric encryption and hashes are much less affected. A quantum attack only halves their effective strength, so AES-256 and SHA-384 remain comfortable. The work is on the public-key side. NIST has standardised replacements: ML-KEM (for key exchange), and ML-DSA and SLH-DSA (for signatures). Current OpenSSL supports them:
$ openssl list -signature-algorithms | grep -i ml-dsa
{ 2.16.840.1.101.3.4.3.18, id-ml-dsa-65, ML-DSA-65, MLDSA65 } @ default
$ openssl genpkey -algorithm ML-DSA-65 -out ml.key
$ ls -l ml.key
-rw------- 1 you wheel 5604 ... ml.key
Note the size: the ML-DSA-65 private key file is about 5.6 KB, against ~240 bytes for a P-256 key. Signatures and certificates grow too. That is why the migration is a project and not a config flag. See the operations checklist.
Quick rules
- Do not invent algorithms or protocols. Use TLS, SSH, age, libsodium. The hard part of cryptography is not the algorithm but the dozens of small details around it (padding, nonces, ordering, error handling). Mature protocols and libraries have already been through these hundreds of times.
- Prefer P-256/P-384 or Ed25519 over RSA for new keys; if RSA, use 3072+. Smaller keys, faster operations, and fewer ways to get the padding wrong.
- Never use MD5 or SHA-1 for signatures. An attacker can build two documents with the same hash, so a signature on one is valid for the other.
- Encryption without authentication (CBC, CTR alone) is a bug. Use GCM or ChaCha20-Poly1305. Otherwise anyone who can modify the data in transit can alter the decrypted result, and you will not know.
- Encryption is not access control, and a hash is not encryption. An encrypted file still needs the right people to hold the key, and a hash cannot be “decrypted” because the data is not in it.
About BastionXP
BastionXP is a cloud-native private PKI CA and device identity management platform that eliminates passwords and shared secrets by issuing hardware-attested certificates to mobile devices and laptops. Secure access to your Wi-Fi, VPN, and SaaS applications in your enterprise network. Replace legacy SCEP with automated ACME Device Attestation. No shared secrets. Zero credential theft. Learn more about BastionXP →