TExcelTAD
Home › Applied Cryptography: Ciphers, Hashes, Signatures, PKI & TLS › Common Crypto Mistakes and Don't Roll Your Own

Common Crypto Mistakes and Don't Roll Your Own

"Don't roll your own crypto" is the most repeated advice in security, and the most misunderstood. It doesn't mean "never write code that calls a cipher". It means: don't design your own primitives, modes or protocols, and don't reimplement standard ones for production, because the failure modes are invisible. Broken crypto passes every functional test: the data decrypts, the signature verifies, the login works. This lesson collects the mistakes from the whole course into one catalogue, with a small detector you can run, and the real systems that made them.

The catalogue

Mistake What goes wrong Lesson Fix
ECB mode equal blocks leak Block Modes AES-GCM / ChaCha20-Poly1305
encryption without authentication malleability, padding oracles Padding Oracle AEAD; or encrypt-then-MAC
constant or repeated nonce/IV keystream reuse, GCM forgeries Nonce Reuse os.urandom(12) per message, or a durable counter
hash(secret + msg) as a MAC length extension Length Extension HMAC
== on MACs or tokens timing leak HMAC hmac.compare_digest
MD5/SHA-1 where collisions matter forged signatures, certificates MD5 and SHA-1 SHA-256
textbook RSA, PKCS#1 v1.5 encryption malleability, Bleichenbacher RSA, OAEP and PSS OAEP, PSS, or ECC
ECDSA nonce reuse or bias private key recovery ECDSA RFC 6979 or Ed25519
unauthenticated key exchange man in the middle Diffie–Hellman sign the transcript, verify certificates
TLS verification disabled man in the middle Chains trust the private CA instead
random for secrets predictable tokens and keys Randomness secrets
fast hash for passwords offline cracking Password Storage Argon2id, scrypt, bcrypt
keys in code or next to data key theft equals data theft Key Management KMS, envelope encryption
same key for several purposes cross-protocol attacks KDFs HKDF with labels

A tiny misuse detector

Real tools (Semgrep's crypto rules, Bandit, CodeQL, CryptoGuard for Java, the CogniCrypt project) find these patterns in code. The toy below uses regular expressions over a few lines of sample code to show the idea, and prints the fix next to each finding.

python · try it yourself
import re
RULES = [
    (r"MODE_ECB|modes\.ECB\(", "ECB mode leaks patterns", "use AES-GCM or ChaCha20-Poly1305"),
    (r"\b(md5|sha1)\(", "MD5/SHA-1 is broken for collisions", "SHA-256 or SHA-3; for passwords Argon2id"),
    (r"getrandbits\(|\bmt_rand\(", "non-crypto PRNG is predictable", "secrets.token_bytes / secrets.choice"),
    (r"(iv|nonce)\s*=\s*b['\"]", "constant IV or nonce", "fresh nonce per message (os.urandom(12) or a counter)"),
    (r"==\s*(expected_)?(mac|tag|sig)", "non-constant-time comparison", "hmac.compare_digest"),
    (r"verify\s*=\s*False|CERT_NONE", "TLS verification disabled", "keep verification; trust a private CA explicitly"),
    (r"sha256\(\s*(password|pw)", "fast hash for passwords", "Argon2id / scrypt / bcrypt with a salt"),
]
SAMPLE = '''
token = "%x" % rng.getrandbits(64)
nonce = b"000000000000"
c = Cipher(algorithms.AES(k), modes.ECB()).encryptor()
if computed == mac:
    ok = True
h = hashlib.sha256(password.encode()).hexdigest()
r = requests.get(url, verify=False)
d = hashlib.md5(data).hexdigest()
'''
for no, line in enumerate(SAMPLE.strip().splitlines(), 1):
    for pat, why, fix in RULES:
        if re.search(pat, line):
            print(f"line {no}: {why:34} -> {fix}")
line 1: non-crypto PRNG is predictable     -> secrets.token_bytes / secrets.choice
line 2: constant IV or nonce               -> fresh nonce per message (os.urandom(12) or a counter)
line 3: ECB mode leaks patterns            -> use AES-GCM or ChaCha20-Poly1305
line 4: non-constant-time comparison       -> hmac.compare_digest
line 6: fast hash for passwords            -> Argon2id / scrypt / bcrypt with a salt
line 7: TLS verification disabled          -> keep verification; trust a private CA explicitly
line 8: MD5/SHA-1 is broken for collisions -> SHA-256 or SHA-3; for passwords Argon2id

Seven findings in eight lines. A pattern matcher misses everything that isn't spelled the expected way (a nonce from a counter that resets, a key derived from a timestamp, a check that happens after use), so code review by someone who knows the failure modes stays necessary; the detector is a net, not a proof.

Failure stories

  • WEP (1997): RC4 with a 24-bit IV prepended to the key. IVs repeated within hours on a busy network, and Fluhrer, Mantin and Shamir (2001) showed that RC4's first output bytes leak key bytes for related keys; later refinements of the attack recovered WEP keys in minutes. The integrity check was a CRC-32, which is linear and forgeable.
  • Zoom (2020): Citizen Lab found meetings encrypted with a single AES-128 key in ECB mode, with keys sometimes distributed through servers in other jurisdictions; Zoom moved to AES-256-GCM within weeks.
  • Juniper ScreenOS (2015): the VPN product used Dual_EC_DRBG with a changed constant; unauthorised code changed it again, which would let whoever chose that constant decrypt VPN traffic.
  • The Debian OpenSSL patch (2006–2008), ROCA (2017) and the PS3 signing key (2010): randomness and key generation (RSA, ECDSA).
  • Home-made protocols in messengers: early versions of several messaging apps used unauthenticated encryption or non-standard constructions; academic analyses found practical weaknesses in some (for example the 2015–2016 analyses of Telegram's MTProto 1.0, which was replaced by MTProto 2.0).
  • Microsoft Storm-0558 (2023): a consumer signing key was obtained by attackers and accepted for enterprise tokens because of a validation gap: a key-management and verification failure, not a cipher break.

None of these broke AES, SHA-256 or the discrete logarithm. All of them were in the layers above.

What "don't roll your own" means in practice

  1. Use high-level, misuse-resistant APIs: libsodium / PyNaCl (SecretBox, Box, secretstream), Tink, cryptography's Fernet and AEAD classes, age for files, the platform's TLS. They choose algorithms, nonces and encodings for you.
  2. Use standard protocols instead of inventing them: TLS 1.3, Noise, Signal's protocol, HPKE (RFC 9180), JOSE/COSE with safe algorithm choices, OAuth/OIDC.
  3. Reach for hazmat only when you must, and then get the design reviewed. The cryptography library calls its low-level layer "hazardous materials" for a reason.
  4. Write it down: a one-page design (goals, threat model, algorithms, key lifecycle, what happens on compromise) catches most mistakes before code exists.
  5. Plan for change (crypto agility): version fields in formats, algorithm ids in data, key ids, so the next migration is a configuration change.

Writing your own cipher, hash or protocol is an excellent way to learn, as this course's toys show. The rule is about production.

How these mistakes are detected

  • Static analysis and secret scanning in CI; dependency checks for known-vulnerable crypto libraries.
  • Code review checklists built from the catalogue; reviews by someone outside the team for anything in hazmat.
  • Known-answer tests against standard vectors, negative tests (tampered ciphertext must fail, wrong key must fail, expired certificate must fail), and fuzzing of parsers.
  • External assessments for protocols and products that ship cryptography.

How they are fixed

Each row of the catalogue has its fix. The general fix is to remove choices: one library, one AEAD, one password hash, one KMS, with wrappers that make the safe way the easy way.

Pitfalls

  • Treating "we use AES-256" as a security review.
  • Fixing one finding (ECB → CBC) and introducing the next (CBC without MAC).
  • Ignoring the tests that matter: crypto code needs tests that should fail to fail.

Practice

1. Which findings would the toy detector miss in: nonce = counter.to_bytes(12, "big") where counter = 0 at every start?

All of them: the nonce isn't a literal, so the constant-nonce rule doesn't match, yet it repeats after every restart. Only review (or a runtime check for duplicate nonces) finds it.

2. Write a negative test for an encryption helper.

Encrypt a message, flip one byte of the ciphertext (and separately of the nonce, the AAD and the tag), and assert that decryption raises the library's authentication error in each case. Also assert that two encryptions of the same message differ.

3. A team wants to "add a bit of XOR obfuscation" on top of TLS for extra security. What do you answer?

It adds no security against anyone who can read the client code (Kerckhoffs), adds bugs and complexity, and may hide real problems. If application-layer confidentiality is needed beyond TLS, use a standard AEAD or HPKE with proper keys.

Test yourself

What does 'don't roll your own crypto' mean in practice?

  1. Never write code that uses encryption
  2. Don't design your own primitives or protocols or reimplement them for production; use standard, reviewed libraries and protocols
  3. Only use hardware encryption
  4. Always write your own AES for control

Why don't broken crypto implementations fail functional tests?

  1. They always crash
  2. The data still decrypts and signatures still verify; the weakness is only visible to an attacker
  3. Test frameworks skip crypto
  4. They are too slow to test

What was wrong with WEP's integrity check?

  1. It used SHA-1
  2. It was a CRC-32, which is linear and forgeable
  3. It used HMAC with a short key
  4. It didn't exist

Which design habit makes future algorithm migrations easier?

  1. Hard-coding the algorithm
  2. Including version and algorithm ids and key ids in formats (crypto agility)
  3. Using one key forever
  4. Encrypting twice