Why You Don't Roll Your Own Crypto
Applied Crypto & Common Pitfalls · Networking & Cryptography track
7 min read
In this module
The Most Dangerous Advice in Software
There's a saying in the security community that gets repeated until it becomes furniture: don't roll your own crypto. The advice is a hard-earned lesson from decades of watching smart, capable engineers build cryptographic systems that were subtly, catastrophically broken.
Why Cryptography Is Uniquely Unforgiving
In most software, a bug means a wrong output, a crash, or a performance hiccup. In cryptography, a bug can silently obliterate all your security while the system looks fine. The ciphertext is random-looking. The decryption round-trips. Every unit test goes green. Meanwhile, an attacker is reading every byte of your traffic.
The difference is the adversarial model. Normal software runs in a benign world — users who want the thing to work. Cryptographic software runs in a hostile one, surrounded by adversaries who actively probe, manipulate, and analyse every observable behaviour for chinks.
Take a small example. Suppose your encryption function takes a few nanoseconds longer when the key has more 1-bits. No real user would ever notice. An attacker, though, will measure timing differences over thousands of requests, run the numbers, and recover your key bit by bit. Not theoretical. Done in the wild against shipping systems.
Cryptographic correctness is not the same as functional correctness. Code that encrypts and decrypts correctly can still be completely insecure due to side-channel leaks, nonce reuse, improper key derivation, or dozens of other subtle issues that do not affect functionality.
Real-World Failures
Sony PS3 key recovery (2010): Sony's ECDSA implementation reused the same random nonce for every signature. The maths demands a unique nonce per signature; reusing it makes the private key trivially recoverable. Sony's code worked perfectly on the surface — signatures generated, signatures verified — but every signed firmware was forgeable. The whole PS3 security model collapsed on a single repeated number.
Heartbleed (2014): A missing bounds check in OpenSSL's heartbeat extension let attackers siphon up to 64 KB of server memory per request, including private keys, session tokens, and user data. The bug lived for two years before discovery and touched roughly 17% of all HTTPS servers. Not a flaw in the cryptographic algorithm — a textbook C programming bug in the implementation around it.
Debian OpenSSL random number generator (2006-2008): A Debian maintainer removed a line of code that looked like a bug (it tripped warnings from memory-checking tools such as Valgrind). The line was seeding the random number generator. Without it, the RNG was reduced to 32,768 possible states, and every key generated on Debian systems became trivially predictable. SSH keys, SSL certificates, GPG keys — all compromised. The fix was a one-line patch. The fallout dragged on for years.
WEP encryption (2001): WEP used RC4 with a 24-bit initialisation vector. Only 16 million possible IVs, which on a busy network collide constantly. Tools like aircrack passively scoop up enough packets and recover the WEP key in minutes. WEP wasn't broken by attacking RC4 directly. It was broken by surrounding RC4 with absurdly short IVs.
What Can Go Wrong
The attack surface of a cryptographic implementation is vast:
Algorithm misuse: Using ECB instead of GCM. Encrypting without authenticating. Reaching for a plain hash where you needed an HMAC. Reusing one key across unrelated purposes. Each of these is a common, catastrophic blunder that can hollow out your security even when the underlying algorithm is mathematically perfect.
Implementation bugs: Off-by-ones in buffer handling. Integer overflows in length calculations. Padding validation that's almost-but-not-quite right. Wrong byte order in key derivation. Garden-variety bugs that turn into shipping vulnerabilities the moment they touch a cryptographic surface.
Side channels: Timing variations that betray secret data. Cache access patterns that leak key bits. Power consumption that correlates with secret operations. Error messages that hint at internal state. Acoustic emanations from CPUs. Even the LED on your hard drive has been used to exfiltrate cryptographic state.
Random number failures: Insufficient entropy. Predictable seeds. Reused nonces. Biased output. Randomness is the bedrock under almost all cryptographic security, and quietly getting it wrong is much easier than you'd hope.
Every category here has been used to flatten the security of real shipping systems.
Try spotting them. Each snippet below encrypts, hashes or verifies something, and each works perfectly in testing. Name the flaw in each before opening the answers.
1. ciphertext = AES_128_ECB_encrypt(key, customer_record)2. iv = bytes(16) # all zeros, every message ciphertext = AES_CBC_encrypt(key, iv, message)3. if received_tag == hmac_sha256(key, body): accept()4. db.store(user, md5(password))5. srand(time(NULL)); for (i = 0; i < 16; i++) key[i] = rand();6. const char *API_KEY = "prod-key-2019-do-not-share"; /* in the shipped binary */Show the answers
- ECB: identical 16-byte blocks of the record encrypt identically, so structure leaks. Use an AEAD such as AES-GCM.
- A fixed IV makes CBC deterministic: the same message always gives the same ciphertext, and shared prefixes show up as shared ciphertext blocks. CBC IVs must be unpredictable, fresh for every message.
==usually stops at the first differing byte, which leaks timing. Use a constant-time comparison such ashmac.compare_digestorCRYPTO_memcmp.- MD5 is fast and unsalted here, so one GPU tries billions of guesses a second and identical passwords share a hash. Use a slow, salted password hash: Argon2id, scrypt or bcrypt.
rand()isn't a cryptographic generator, and seeding it with the time leaves only as many keys as there are plausible seconds. The program below recovers one.- Anyone with the binary has the key (
stringswill find it). Load secrets from the environment or a secrets manager, and rotate this one now.
Here's flaw 5 in action. The attacker knows roughly when the key was made, so they replay srand() for every second in a 24-hour window until the output matches.
A 128-bit key should take 2^128 guesses. This one takes at most 86,400.
What to Use Instead
Use established, peer-reviewed cryptographic libraries:
libsodium (NaCl): A high-level API that's borderline impossible to misuse. Functions like crypto_secretbox handle encryption and authentication together, with no modes or padding to choose. You still supply a unique nonce per message, but at 24 bytes it's long enough to fill from randombytes_buf() without worrying about collisions. The recommended starting point for most applications. The API is shaped so that the easiest path is also the correct one.
OpenSSL / BoringSSL: The most widely deployed cryptographic library on Earth. Lower level than libsodium, with more opportunities to shoot yourself in the foot, but battle-tested and feature-rich. Google's BoringSSL fork has trimmed out rarely-used features to shrink the attack surface.
Language standard libraries: Go's crypto package, Rust's ring crate, and Python's cryptography library all ship well-reviewed implementations with safe APIs. The maintainers know the cryptographic theory and the implementation traps in equal measure.
When Studying Crypto Is Valuable
Understanding cryptography is not the same as implementing it. Studying how these systems work helps you:
- Choose the right algorithm and mode for your use case
- Recognise when a system is misconfigured or misusing cryptographic primitives
- Understand security advisories and CVEs
- Have informed conversations with security teams
- Appreciate why certain design decisions were made
- Audit third-party code that uses cryptographic APIs
The goal is informed usage, not DIY implementation. Know enough to use the tools properly and to smell when something is off. The lessons that follow walk through specific ways that correct-looking crypto can fall apart, so you can spot the patterns in code you encounter in the wild.