Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Handbooks  /  Cryptography for Engineers
Handbook~16 min readSecurityworked math + runnable code
Cryptography for Engineers

One key,
used once.

Encryption sounds like deep math, but its purest form is one operation you already know: XOR. Combine each byte of your message with a byte of a secret key and the result reveals nothing — provably, perfectly — as long as the key is random, as long as the message, and used exactly once. That's the one-time pad, the only cipher that's mathematically unbreakable. Its rules also teach the whole subject: break any one of them (especially "used once") and secrecy collapses instantly. This handbook builds encryption from XOR up, and shows why the mistakes matter more than the algorithms.

01

Encryption is XOR

Strip encryption down to its essence and it's a reversible scramble: turn readable plaintext into ciphertext that looks like noise, in a way only someone with the secret can undo. The simplest operation that does this is XOR — exclusive-or, bit by bit. XOR each bit of the message with a bit of a secret key, and you get ciphertext. The magic is that XOR is its own inverse: apply the same key again and the two XORs cancel, giving back the original. a ⊕ k ⊕ k = a.

That single property — encrypt and decrypt are the same operation with the same key — is the seed of all symmetric cryptography. The ciphertext looks nothing like the plaintext (flip a key bit and the output bit flips), yet anyone holding the key recovers the message exactly. No lookup tables, no reversible math tricks; just XOR. Everything harder in cryptography — block ciphers, stream ciphers, AES — is about making the "key" long enough and unpredictable enough to be safe while staying short enough to be practical. The idea underneath doesn't change.

The one-sentence version

XOR with a random, message-length, single-use key is the one-time pad — provably unbreakable — and every rule it demands (random, as long as the message, used once) is a lesson the rest of cryptography spends its time enforcing.

02

Perfect secrecy

The one-time pad (OTP) is XOR encryption with three conditions on the key: it must be truly random, at least as long as the message, and used only once. Meet all three and the OTP has perfect secrecy — a property proven by Shannon. It means the ciphertext leaks zero information about the plaintext: for any ciphertext an attacker sees, every possible message of that length is equally likely, because there's a key that maps this ciphertext to that message. With no computer, no matter how much time, the attacker cannot do better than guessing.

That's a stronger guarantee than any modern cipher offers — AES is "computationally" secure (safe because breaking it would take longer than the universe has), but the OTP is unconditionally secure. So why doesn't everyone use it? The conditions are brutally impractical: you need a fresh, truly random key as long as the total of everything you'll ever send, and you must share it in advance over some secure channel — which is nearly the same problem encryption was supposed to solve. The OTP is perfect and almost useless, which is exactly why it's the right thing to study: it shows what secrecy is, and every practical cipher is a trade against its impracticality.

03

The fatal mistake

Of the three rules, "used once" is the one that kills real systems, and the reason is pure XOR algebra. Encrypt two messages with the same key and look at what an attacker can compute from the two ciphertexts:

Why reusing the key destroys secrecy
c₁= p₁ ⊕ k   (first message, encrypted with key k)
c₂= p₂ ⊕ k   (second message, same key k)
c₁ ⊕ c₂= (p₁ ⊕ k) ⊕ (p₂ ⊕ k) = p₁ ⊕ p₂   — the key cancels!
ResultAttacker has p₁ ⊕ p₂ with no key — language stats or a known crib recover both.

The key vanishes. The attacker is left with the XOR of the two plaintexts, and human language is redundant enough that this is often enough to unravel both messages — no key ever recovered. This "two-time pad" blunder has broken real ciphers in history (it's how the VENONA project read Soviet cables). The lesson generalizes far beyond the OTP: never reuse a keystream. It's why every modern cipher pairs the key with a unique, per-message nonce — so the actual encryption stream is different every single time, even when the key is the same.

04

The XOR math

Encryption and decryption are the same XOR, so decrypting recovers the plaintext exactly, and the ciphertext differs from the plaintext (bits flip wherever the key is 1):

c  =  p ⊕ k     decrypt:  c ⊕ k  =  (p ⊕ k) ⊕ k  =  p

Same operation both ways. A zero key is the identity (p ⊕ 0 = p) — encrypts nothing — which is why the key must be nonzero and random.

Reusing the key on two messages cancels it, exposing the XOR of the plaintexts — the fatal leak:

c1 ⊕ c2  =  (p1 ⊕ k) ⊕ (p2 ⊕ k)  =  p1 ⊕ p2  (no k)

The key is gone; only the plaintexts' relationship remains. The runnable version below encrypts, round-trips, measures the bit-flips, and demonstrates the key-reuse leak.

RUN IT YOURSELF

The one-time pad, from XOR

Encryption in its purest form is XOR: combine each plaintext byte with a key byte. Because XOR is its own inverse, decrypting is the same operation — XOR again with the same key and the plaintext comes back. The ciphertext looks nothing like the input (bits flip wherever the key is 1). But XOR with a zero key changes nothing, showing why the key must be random and nonzero. And the fatal mistake: reuse the key on two messages and XORing the ciphertexts cancels the key, leaking p1 XOR p2. Change the messages or the key and watch the round-trip, the bit-flips, and the key-reuse leak.

CPython · WebAssembly
05

Scaling to real crypto

Real systems can't ship a message-length key, so cryptography is the art of getting OTP-like safety from a short key. Two families do the work:

KindHow it works · when to use
SymmetricOne shared secret key for both encrypt and decrypt (AES is the standard). Fast — used for the bulk of the data. Hard part: both sides must already share the key.
Public-keyA key pair — a public key anyone can encrypt to, a private key only you can decrypt with. Solves key-sharing with strangers; also enables signatures. Slower, so used to exchange a symmetric key.
HashingOne-way fingerprint (SHA-256) — not encryption. Verifies integrity; salted+slow (Argon2/bcrypt) for passwords.
Nonce / IVA unique per-message value combined with the key so the keystream never repeats — the practical answer to "never reuse a keystream."

The everyday example is TLS — the padlock in your browser. It uses slow public-key crypto once, at the start, to agree on a fresh symmetric key, then switches to fast symmetric encryption (AES) for the actual traffic, with a new nonce per record so no keystream ever repeats. That handshake is the whole subject in miniature: public-key to solve sharing, symmetric for speed, nonces to honor "use once." Understand XOR and the OTP's three rules, and every one of these constructions reads as a practical workaround for a rule you can't literally satisfy.

06

Pitfalls

The cardinal rule: never roll your own crypto. Cryptographic code that encrypts and decrypts perfectly can still be catastrophically broken — a reused nonce, a timing side channel, textbook RSA without padding, a fast hash for passwords. The failures are silent; your tests pass and you're wide open. Use vetted libraries and standard constructions (AES-GCM, libsodium, TLS), and treat "I wrote my own cipher" as a red flag, not a feature.

The specific traps follow the OTP's lessons. Weak randomness: keys and nonces must come from a cryptographically secure random source (`secrets`/`/dev/urandom`), never a normal PRNG seeded by the clock — predictable keys are no keys. Nonce reuse: the two-time-pad mistake in modern dress — reusing a nonce with the same key breaks AES-GCM completely, so nonces must be unique per message. Keys in the wrong place: hardcoded in source, committed to git, or logged — a perfect cipher with a leaked key protects nothing, so keys live in secret managers, not code. And fast password hashing: hash passwords with a deliberately slow, salted function (Argon2, bcrypt), never a bare SHA-256, so a stolen database can't be brute-forced. Get these right and you've captured the entire practical payload of the field: the engineer's job is to use crypto correctly, and every rule traces back to XOR, one key, used once.

Worth knowing

Don't invent crypto — use AES-GCM/libsodium/TLS. Draw keys and nonces from a secure random source, never reuse a nonce with a key, keep keys out of code and logs, and hash passwords with Argon2/bcrypt. Every one of these is the OTP's "random, once" rule in a practical costume.

By the numbers

Worked example: two bytes, one key, used twice

Encrypt "hi" with the first two bytes of the toy key from the code above, 0x9A 0x3C. Then make the fatal mistake: encrypt "no" with the same key, and play the attacker who sees only the two ciphertexts.

StepWhatBitsResult
1Plaintext p₁ = "hi"01101000 0110100168 69
2Key k10011010 001111009A 3C
3c₁ = p₁ ⊕ k11110010 01010101F2 55: 8 of 16 bits flipped
4Decrypt: c₁ ⊕ k01101000 01101001"hi" again
5Reuse: c₂ = "no" ⊕ k11110100 01010011F4 53
6Attacker: c₁ ⊕ c₂00000110 0000011006 06 = p₁ ⊕ p₂, no key needed
7Guess p₁ = "hi" (a crib)06 06 ⊕ "hi""no": the second message
8c₁ ⊕ "hi"F2 55 ⊕ 68 699A 3C: the key itself

Step 6 is the whole attack. The key cancels, and the attacker holds the XOR of two plaintexts. Step 7 shows why that is fatal: one correct guess at one message gives the other for free. Step 8 is worse. It hands over the key, so every other message encrypted with it opens too. Real attacks guess common words, headers or file formats in place of “hi”, and slide them along until readable text falls out.

Trade-offs

Cost and trade-offs: what each construction buys

Here Time means speed, or an attacker’s effort. Space means the key material or state you must keep.

CaseTimeSpaceWhy
One-time padOne XOR per byteA random key as long as all traffic, everUnconditional secrecy. Sharing the key is the entire cost.
AES-GCMFast; modern CPUs have AES instructions128- or 256-bit key, 96-bit nonce, 128-bit tagSecrecy plus integrity. A repeated nonce under one key leaks p₁ ⊕ p₂ and lets an attacker forge tags.
Public-key (X25519, RSA)Orders of magnitude slower than AES32-byte X25519 keys; RSA moduli of 2048 bits or moreSolves sharing with strangers, so it runs once per session to agree a symmetric key.
SHA-256Fast by designNo key; 256-bit outputRight for integrity and fingerprints. Fast is exactly wrong for passwords.
Argon2id / bcryptDeliberately slow and tunableArgon2 also costs memory per guessEach guess costs the attacker what one login costs you.
Brute-forcing AES-1282¹²⁸ keys at an illustrative trillion guesses/s—About 1.1 × 10¹⁹ years. Nobody attacks the cipher. They attack nonces, keys and randomness.
8 lowercase letters26⁸ ≈ 2.1 × 10¹¹ guesses—About 21 s at an illustrative 10 billion fast hashes/s, about 242 days at 10,000 slow hashes/s.

The last two rows are the practical lesson. A good cipher is effectively unbreakable by search. A password space is small, so only the cost per guess protects it.

In the wild

Where this shows up in production and interviews

  • TLS 1.3

    Every handshake runs an ephemeral Diffie-Hellman exchange (often X25519), then protects records with an AEAD: AES-GCM or ChaCha20-Poly1305. Each record’s nonce comes from a sequence number, so no keystream repeats. TLS 1.3 dropped RSA key transport, so a stolen server key cannot decrypt recorded old sessions.

  • WEP: the two-time pad, shipped

    WEP Wi-Fi encrypted packets with an RC4 keystream chosen by a 24-bit IV. That is only 16,777,216 values, and by the birthday bound a repeat becomes more likely than not after about 4,800 packets. Every repeat is step 6 of the example above.

  • Encryption at rest

    Envelope encryption: a fresh data key encrypts each object with AES-GCM, and a master key held in a KMS encrypts that data key, which is stored beside the data. The master key never leaves the KMS, and rotating it means re-wrapping small data keys, not re-encrypting the data.

  • The interview version

    “How do you store passwords?” Argon2id or bcrypt with a per-user salt, compared in constant time. “Encrypt this column.” An AEAD from a vetted library, a unique nonce per value, and the key in a KMS rather than in config. Then say what you would never do: reuse a nonce, use a clock-seeded PRNG, or invent a cipher.

Self-check

Check yourself

A service restarts and its AES-GCM nonce counter starts again at 0, under the same key. What can an attacker do?

Every nonce now repeats, so every keystream repeats. XOR two ciphertexts that share a nonce and the attacker gets p₁ ⊕ p₂, exactly as in step 6. GCM is worse than the bare pad here: a repeat also leaks the authentication key, so tags can be forged. Fix it with random 96-bit nonces (staying under NIST’s 2³² messages per key), a counter that is persisted across restarts, or a fresh key per boot.

An attacker sees a pad-encrypted message they know reads "PAY $100". Can they make it say $900 without the key?

Yes. XOR the ciphertext byte that holds 1 (0x31) with 0x08, and it decrypts to 9 (0x39). The pad gives perfect secrecy but no integrity. That is why real systems use an AEAD such as AES-GCM: the tag check fails and the edited message is rejected.

A pad is generated with random.random() seeded from the clock in seconds. Is it still a one-time pad?

No. The whole pad follows from the seed, so the attacker only has to try seeds, not keys. One day has 86,400 seconds, which is a laptop’s work. Truly random means a CSPRNG such as secrets or /dev/urandom.

A breached database stored salted SHA-256 password hashes. Why is that still bad, and what changes with Argon2id?

The salt stops precomputed tables and hides users who share a password, but each guess still costs one fast hash. By the trade-offs table, every 8-lowercase-letter password falls in seconds at an illustrative 10 billion guesses a second. Argon2id makes each guess slow and memory-hungry, so the same search takes months per user.

Frequently asked

Quick answers

What is the one-time pad?

XOR each byte with a random, message-length, single-use key. It's provably unbreakable — perfect secrecy — but impractical because the key is huge.

Why can't you reuse a key?

XORing two ciphertexts made with the same key cancels the key: c1⊕c2 = p1⊕p2, and language stats recover both plaintexts.

Symmetric vs public-key?

Symmetric shares one key (fast, AES); public-key uses a keypair so strangers can encrypt to you (slower). TLS uses public-key to exchange a symmetric key.

What should engineers never do?

Roll their own crypto, reuse nonces, use weak randomness, hardcode keys, or fast-hash passwords. Use vetted libraries and standards.

▶  Watch it explained

Proof of work: how a ledger stays unforgeable with no bank

Zero-knowledge proofs: prove a secret without revealing it

Finished this one? 0 / 209 Handbooks done
NextThe System Design Fundamentals Handbook Closest handbook to this one

Explore the topic

See this alongside everything else on the same subject — handbooks, system designs, challenges and tools, in one place.

More Handbooks