Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 40 ยท Practice and Review

Common Cryptography Mistakes

Learn the cryptography mistakes that break real systems: home-made crypto, ECB mode, hard-coded keys, MD5 passwords, nonce reuse and weak randomness, plus a checklist.

Most real-world cryptography failures do not come from someone breaking AES or SHA-256. They come from using good tools badly: the wrong mode, a key committed to a repository, a nonce used twice, a password hashed with a fast function. These mistakes are common because the code still works. The program encrypts, decrypts and passes its tests. It is only insecure, and nothing in the output tells you.

This lesson walks through the mistakes you will meet most often. For each one you see why it fails, a small demonstration you can run, and the safer alternative. A checklist at the end condenses everything into questions you can ask during a code review.

Mistake 1: Rolling your own crypto

Inventing a cipher, a hash or a protocol is the root of many other mistakes. Schneier's famous observation is that anyone can design a cipher they cannot break themselves; the difficulty is designing one that others, with years of effort, cannot break either. Published algorithms survive public attacks. Your clever scheme has not.

Home-made constructions tend to share the same flaws: they preserve statistics (so patterns survive), they have no proof of strength, and they miss attacks that specialists know by name, such as chosen-ciphertext attacks and padding oracles. A typical example is a home-made hash that "looks" scrambled but is just a sum of bytes; you will break one in the third editor below.

Do instead: use a high-level, widely reviewed library, pick the primitive with the highest-level API that fits (for example an authenticated-encryption box rather than a raw cipher), and let experts own the details.

Mistake 2: ECB mode and unauthenticated encryption

A block cipher encrypts one block at a time. In ECB mode each block is encrypted independently with the same key, so identical plaintext blocks produce identical ciphertext blocks. The result leaks the structure of the data: repeated values, and in a famous demonstration with images, the outline of a picture. Modes with an IV or nonce (CBC, CTR, GCM) hide repetition (modes of operation).

A second, quieter problem is encrypting without authentication. Ciphertext without a MAC can be modified in transit: flipping bits in CTR mode flips the same bits of the plaintext, and CBC is open to padding-oracle attacks. Do instead: use authenticated encryption such as AES-GCM or ChaCha20-Poly1305 (authenticated encryption), which detects any change.

flowchart LR
    P["Plaintext blocks:<br/>A, A, B, A"] --> E["ECB"]
    P --> C["CBC or CTR with IV"]
    E --> E2["Ciphertext: X, X, Y, X<br/>(pattern visible)"]
    C --> C2["Ciphertext: P, Q, R, S<br/>(no visible pattern)"]

ECB maps equal blocks to equal blocks; chained or counter-based modes do not.

The next editor uses a small toy block cipher (a Feistel network built on HMAC), written here only so the lesson runs without libraries. Watch what happens to the repeated block.

Python ECB repeats blocks, CBC does not

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The third line of the plaintext is different, and its ciphertext is different too, but the three identical lines share one ciphertext. An observer learns that block 1, 2 and 4 are equal without knowing the key. In real data that might be a repeated header, a common padding block, or the same salary value in several records.

Mistake 3: Reusing a nonce or IV

Stream ciphers and counter-based modes turn a key into a keystream. The nonce makes the keystream different for every message. If the same (key, nonce) pair encrypts two messages, XORing the ciphertexts cancels the keystream and gives the XOR of the plaintexts, which an attacker can untangle with guesses (the two-time pad). In AES-GCM a repeated nonce is even worse: it also leaks the authentication key.

The same lesson applies to comparing secrets. Checking a MAC tag with ordinary == stops at the first different character, so the time taken reveals how many characters were right. An attacker can recover a tag one character at a time. The demonstration below counts comparison steps instead of measuring time, so the result is exact.

Python Nonce reuse and leaky comparisons

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Do instead: generate a fresh random nonce for every message (or use a counter that never repeats and survives restarts), send it alongside the ciphertext, and compare secrets with hmac.compare_digest.

Mistake 4: Fast hashes for passwords

MD5, SHA-1 and plain SHA-256 are designed to be fast. That is great for checksums and terrible for passwords: an attacker with a stolen table can test enormous numbers of guesses per second. MD5 is additionally broken against collisions, but even a strong fast hash is the wrong tool here. Passwords need a slow, salted function: scrypt, Argon2 or PBKDF2 (password hashing).

The editor below also shows two more mistakes: a home-made hash (a plain sum of bytes, which collides trivially when you rearrange the letters) and a "random" token from a seeded generator, which an attacker can regenerate by trying the seeds around the time of issue.

Python MD5 passwords, a toy hash and predictable tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The third demo is the one that surprises people. Python's random module is perfectly good for simulations and games, but it is deterministic: the same seed gives the same stream, and its internal state can even be reconstructed from output. For anything an attacker must not guess, such as session ids, reset tokens, keys and nonces, use secrets or os.urandom (randomness and entropy).

Mistake 5: Hard-coded keys and secrets in the code

A key that lives in the source code lives everywhere: in the repository history, in every clone, in build logs, in container images. Deleting it in a later commit does not remove it from history. The mistake is read-only to show, because the damage is not in how it runs but in where it sits:

Python
# Do not do this
SECRET_KEY = b"hunter2-super-secret-key-1234567"   # in source control forever

def encrypt(data):
    return aes_gcm_encrypt(SECRET_KEY, data)

The same applies to API tokens, database passwords and private keys. Safer patterns:

Python
import os

# Read the secret at start-up from the environment or a secret manager
secret_key = bytes.fromhex(os.environ["APP_ENCRYPTION_KEY"])

Better still, keep keys in a key management service or a hardware module, give each environment its own key, rotate keys on a schedule, and derive purpose-specific subkeys instead of using one key for everything (key derivation and management). If a secret is ever committed, treat it as leaked: rotate it, do not just delete it.

A related slip is deriving a key straight from a short password, such as sha256(password). The key then has only as much entropy as the password. Use a password-based KDF with a salt and a high work factor.

Mistake 6: Weak or misused randomness, small keys and skipped checks

A few more repeat offenders from code reviews:

  • Too small keys. RSA below 2048 bits or symmetric keys below 128 bits. See Break Weak Crypto for what a 60-bit RSA key is worth.
  • Textbook RSA without padding. Encrypting raw numbers allows malleability and small-exponent attacks. Use OAEP for encryption and PSS for signatures (RSA padding and pitfalls).
  • Skipping certificate validation. Passing verify=False to an HTTP client to silence an error removes all protection against an active attacker.
  • Encrypting when you meant to hash, or encoding when you meant to encrypt. Base64 is an encoding, not secrecy (encoding vs encryption).
  • Logging secrets. Keys, tokens and passwords end up in log files, error messages and crash dumps.
  • Ignoring errors. A failed MAC check must stop processing. Returning partially decrypted data, or distinguishing "bad padding" from "bad MAC" in error messages, creates an oracle.

A review checklist

Question Safe answer
Did we invent any primitive or protocol? No; a vetted library handles it
Which mode encrypts the data? An AEAD mode: AES-GCM or ChaCha20-Poly1305
How do we make nonces? Random or counter, never reused under one key
Where do keys live? A secret manager or KMS, not source control
How are passwords stored? Argon2id, scrypt or PBKDF2 with a per-user salt
Where does randomness come from? secrets / os.urandom, never random
How are MAC tags compared? hmac.compare_digest
What key sizes are used? RSA 2048+, AES 128+, curves such as P-256 or X25519
Is certificate validation on? Yes, with no verify=False
Can we rotate a key without downtime? Yes, and we have tried it

If you can answer every row confidently, you have avoided most of the failures that make the news.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does ECB mode leak?

    ECB encrypts each block independently, so repetition in the plaintext shows up as repetition in the ciphertext.
  2. 2. Why is it dangerous to encrypt two messages with the same key and nonce in a stream cipher or CTR mode?

    The same (key, nonce) pair produces the same keystream, so the two-time-pad attack applies.
  3. 3. Why is SHA-256 alone a poor way to store passwords?

    Password hashing should be slow and salted. A fast hash makes guessing cheap, even though the hash itself is strong.
  4. 4. A developer commits an API key by mistake and deletes it in the next commit. What should happen next?

    The key remains in the repository history and in any clone. Rotating it is the only safe response.
  5. 5. Which source should you use for a password-reset token?

    secrets draws from the operating system's CSPRNG, which an attacker cannot predict. Seeded or counter-based values can be regenerated or guessed.

Summary

  • Do not invent cryptography; use vetted libraries and the highest-level API that fits.
  • ECB leaks repetition; use an authenticated mode (AES-GCM, ChaCha20-Poly1305) so that tampering is detected.
  • Never reuse a (key, nonce) pair, and compare secrets with hmac.compare_digest.
  • Store passwords with Argon2id, scrypt or PBKDF2, with a unique salt; never with MD5 or plain SHA-256.
  • Generate secrets with secrets or os.urandom, not with random.
  • Keep keys out of source control, rotate them, and treat any leaked key as compromised.

Next: Cryptography Interview Questions.