0Pricing
Cryptology Academy · Lesson

Common Python Crypto Pitfalls & Secure Patterns

Avoid hardcoded keys, ECB mode, non-constant-time compares, and more.

Common Python Crypto Pitfalls & Secure Patterns is a free Cryptology Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Cryptology Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

The Most Dangerous Crypto Mistakes

Cryptography is easy to use wrong. The most common Python pitfalls: hardcoded keys, ECB mode, non-constant-time comparisons, weak randomness, key/nonce reuse, and rolling your own crypto.

Pitfall 1: Hardcoded Keys

Never embed keys in source code. They end up in git history, logs, and error messages. Use environment variables or a KMS:

# WRONG
SECRET_KEY = b"my_secret_key_12"  # visible in git!

# RIGHT
import os
SECRET_KEY = os.environb.get(b"SECRET_KEY") or os.urandom(32)
# Or load from KMS at startup

Pitfall 2: ECB Mode

AES-ECB encrypts each block independently — identical plaintext blocks produce identical ciphertext blocks. The "ECB penguin" attack reveals patterns in images and structured data. Always use GCM or CBC with random IV.

# WRONG — never use ECB
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
cipher = Cipher(algorithms.AES(key), modes.ECB())  # insecure!

# RIGHT
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
aesgcm = AESGCM(key)  # authenticated encryption

Pitfall 3: Non-Constant-Time MAC Comparison

Using == to compare MACs leaks timing information. Always use hmac.compare_digest:

import hmac

# WRONG — leaks timing
if received_mac == expected_mac:
    pass

# RIGHT — constant-time
if hmac.compare_digest(received_mac, expected_mac):
    pass

Pitfall 4: Weak Random Number Generation

Never use random module for cryptographic purposes — it is not a CSPRNG. Use secrets or os.urandom:

import random, secrets, os

# WRONG
key = bytes([random.randint(0, 255) for _ in range(32)])  # predictable!

# RIGHT
key = os.urandom(32)          # OS CSPRNG
token = secrets.token_bytes(32)  # secrets module wrapper

Pitfall 5: IV/Nonce Reuse

Reusing an IV with CBC or a nonce with GCM breaks security. Generate a fresh random IV/nonce for every encryption and store it alongside the ciphertext:

import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

key = AESGCM.generate_key(bit_length=256)
aesgcm = AESGCM(key)

# WRONG — fixed nonce
nonce = b"\x00" * 12  # reuse breaks GCM!

# RIGHT — fresh nonce every time
nonce = os.urandom(12)
ciphertext = aesgcm.encrypt(nonce, b"data", None)

Pitfall 6: Using MD5 or SHA-1 for Security

MD5 and SHA-1 are cryptographically broken for collision resistance. Never use them for digital signatures, certificate fingerprints, or HMAC. Use SHA-256 or SHA-3-256.

Pitfall 7: Rolling Your Own Crypto

Implementing cryptographic primitives from scratch almost always introduces subtle bugs. Use cryptography, PyNaCl, or PyCA packages. Never implement AES, RSA, or ECDSA yourself.

Secure Pattern: PyNaCl for High-Level Crypto

PyNaCl wraps the NaCl/libsodium library — an opinionated, hard-to-misuse API:

# pip install PyNaCl
import nacl.secret
import nacl.utils

key = nacl.utils.random(nacl.secret.SecretBox.KEY_SIZE)
box = nacl.secret.SecretBox(key)

encrypted = box.encrypt(b"my secret message")
decrypted = box.decrypt(encrypted)
print("Decrypted:", decrypted)  # Uses XSalsa20-Poly1305

Secure Pattern: Password Hashing with Argon2

Use argon2-cffi for password hashing — never SHA-256 or bcrypt directly:

# pip install argon2-cffi
from argon2 import PasswordHasher

ph = PasswordHasher(time_cost=3, memory_cost=65536, parallelism=4)
hash_val = ph.hash("user_password")
print("Hash:", hash_val[:40], "...")

# Verify
try:
    ph.verify(hash_val, "user_password")
    print("Password correct")
except Exception:
    print("Wrong password")

Key Zeroisation

After using a key in memory, zero it out to reduce window for memory-dump attacks. Python's GC makes this hard — use ctypes or PyNaCl which handles this automatically.

Knowledge Check

Which Python function must be used instead of == when comparing cryptographic MACs?

Lesson Recap

Avoid hardcoded keys, ECB mode, == for MAC comparison, random module, and nonce reuse. Use os.urandom/secrets for randomness, AESGCM for encryption, hmac.compare_digest for verification. PyNaCl and argon2-cffi provide safe high-level APIs for symmetric crypto and passwords.

Frequently asked questions

Is the “Common Python Crypto Pitfalls & Secure Patterns” lesson free?

Yes — the full text of “Common Python Crypto Pitfalls & Secure Patterns” is free to read here on the web, and the Cryptology Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Cryptology Academy course, upgrade to CoddyKit PRO.

What will I learn in “Common Python Crypto Pitfalls & Secure Patterns”?

Avoid hardcoded keys, ECB mode, non-constant-time compares, and more. You practise Cryptology Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Cryptology Academy?

No prior experience is required. Cryptology Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Common Python Crypto Pitfalls & Secure Patterns” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Cryptology Academy lesson?

Yes. Every Cryptology Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Python cryptography Library Overview
  2. AES-GCM Encrypt & Decrypt in Python
  3. RSA & ECDSA Key Pairs in Python
  4. Common Python Crypto Pitfalls & Secure Patterns
← Back to Cryptology Academy