Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 40 ยท Practice and Review

Cryptography Cheat Sheet

A one-page cryptography cheat sheet: which primitive fits which job, safe parameters, hashlib, hmac and secrets snippets, and a do and don't table.

This page is a compact reference for the whole Cryptography tutorial. It answers three questions quickly: which primitive do I need, which parameters are safe, and what does the Python code look like. It is not a replacement for the lessons. Every section links to the lesson that explains the idea, and the examples can be run and changed.

One rule sits above all the tables: use a well-reviewed library for real systems, and treat the from-scratch code in this tutorial as a learning tool. The numbers below are typical guidance at the time of writing, so check current recommendations before you ship.

Which primitive for which job

Start from the goal, not from the algorithm. Most mistakes come from picking a tool that solves a different problem.

Job Use Not this
Keep data secret and unmodified Authenticated encryption (AES-GCM, ChaCha20-Poly1305) Plain AES-ECB or AES-CBC without a MAC
Detect accidental changes in a file A hash such as SHA-256 A CRC when an attacker is involved
Prove a message came from a key holder (shared key) HMAC-SHA-256 sha256(key + message)
Store a password scrypt, Argon2id or PBKDF2 with a salt A plain hash, MD5, SHA-1
Derive several keys from one secret HKDF Reusing one key for everything
Turn a password into an encryption key A password KDF (scrypt, Argon2id, PBKDF2) A single fast hash
Generate keys, tokens, nonces, salts secrets / os.urandom random
Agree on a shared key over an open channel X25519 / ECDH (or DH with large groups) Sending the key in the clear
Encrypt to someone you have never met Hybrid: public-key key exchange plus symmetric AEAD Raw RSA on long messages
Sign so anyone can verify Ed25519, ECDSA or RSA-PSS Textbook RSA, hashing alone
Hide the encoding, not the meaning Nothing: base64 and hex are not secrecy Calling base64 "encryption"

Background: what cryptography is, encoding vs hashing vs encryption, public-key ideas.

flowchart TD
    A["What do you need?"] --> B{"Secrecy?"}
    B -- yes --> C["AEAD cipher<br/>(AES-GCM / ChaCha20-Poly1305)"]
    B -- no --> D{"Who must verify?"}
    D -- "only me / shared key" --> E["HMAC"]
    D -- "anyone" --> F["Digital signature"]
    D -- "nobody, just integrity" --> G["Hash"]
    C --> H{"Keys shared in advance?"}
    H -- no --> I["Key exchange<br/>(X25519) + KDF"]

A decision path from the goal to the primitive.

Hash functions

A cryptographic hash maps any input to a fixed-size digest. It must be fast, one-way, and collision resistant (hash functions).

Algorithm Digest Status
MD5 128 bits Broken for collisions. Never for security.
SHA-1 160 bits Broken for collisions. Avoid.
SHA-256 / SHA-512 256 / 512 bits Good. Vulnerable to length extension if misused as a MAC.
SHA3-256 256 bits Good. No length extension.
BLAKE2b / BLAKE2s up to 512 / 256 bits Good and fast. Has a built-in keyed mode.

The birthday bound means a collision needs about 2^(n/2) work for an n-bit digest, so 256 bits gives roughly 128 bits of collision security (hash attacks).

Keyed tools: MACs and key derivation

  • HMAC authenticates a message with a shared key. Compare tags with hmac.compare_digest, never with == (MACs and HMAC).
  • HKDF stretches one good secret into many independent keys, using a different info label for each purpose (key derivation).
  • Password KDFs make each guess expensive (password hashing).
Tool Typical parameters
PBKDF2-HMAC-SHA256 600,000 or more iterations, 16-byte random salt
scrypt N = 2^15 or higher, r = 8, p = 1, 16-byte random salt
Argon2id at least 19 MiB memory, 2 iterations, 1 lane (raise as hardware allows)
Salt 16 random bytes per password, stored next to the hash

Run it: hashing, HMAC and random bytes

This example uses only the standard library. It prints the digest of a known test string, shows that HMAC depends on the key, and generates secure random values (only their lengths are printed, because they differ every run).

Python hashlib, hmac and secrets in one place

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 first line is the standard SHA-256 test value for abc. Notice that the tags in step 2 differ, because the key is part of the computation.

Symmetric encryption

Need Choice
Default AES-256-GCM or ChaCha20-Poly1305 (both are AEAD: they encrypt and authenticate)
Key size 128 or 256 bits for AES, 256 bits for ChaCha20
Nonce 96 bits for GCM and ChaCha20-Poly1305, unique for every message under one key
Associated data Headers you want authenticated but not encrypted
Never ECB mode, unauthenticated CBC or CTR, a reused nonce

Key facts:

  • A block cipher like AES works on 128-bit blocks and needs a mode to handle longer data (block ciphers, modes of operation).
  • ECB leaks patterns. CBC needs padding and is malleable. CTR turns the cipher into a stream cipher, so reusing a nonce reveals the XOR of two plaintexts (stream ciphers).
  • XOR with a random, single-use, key-sized pad is perfectly secret, and reusing the pad destroys it (one-time pad).
  • Encrypt then MAC the ciphertext, or use an AEAD that does it for you (authenticated encryption).

Public-key cryptography

Task Modern choice Notes
Key exchange X25519 (ECDH) Gives forward secrecy when keys are ephemeral
Signatures Ed25519 Deterministic, no per-signature nonce to leak
Signatures (legacy) ECDSA P-256, RSA-PSS ECDSA breaks if a nonce is reused (signatures)
Encryption (legacy) RSA-OAEP Only for short data such as a session key
Approximate equal strength Symmetric bits RSA / DH modulus Elliptic curve
Minimum today 112 2048 224
Common default 128 3072 256
High 256 15360 512

Remember: Diffie-Hellman is a key agreement, not encryption, and unauthenticated exchange is open to a man in the middle. RSA without padding is malleable and deterministic (padding pitfalls). Elliptic curves give the same security with much smaller keys.

Math you keep using

Idea Python
Modular exponentiation pow(a, b, m)
Modular inverse pow(a, -1, m) (needs gcd(a, m) == 1)
GCD math.gcd(a, b)
Fermat test (prime p) pow(a, p - 1, p) == 1
Euler's theorem pow(a, phi(n), n) == 1 when gcd(a, n) == 1
RSA c = pow(m, e, n), m = pow(c, d, n), d = pow(e, -1, phi)

See modular arithmetic, the extended Euclidean algorithm, primality testing and Euler and CRT.

Run it: the math one-liners

This example checks several identities from the table. All results are exact integers, so the output is the same every time.

Python Modular arithmetic cheat checks

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.

Random numbers

Python
import random, secrets

random.random()            # NOT secure: predictable once its state is known
secrets.token_bytes(32)    # raw key material
secrets.token_hex(16)      # hex string, 32 characters
secrets.token_urlsafe(32)  # for URLs and tokens
secrets.randbelow(100)     # secure integer in [0, 100)
secrets.choice("abcdef")   # secure choice

Rules: keys, salts, nonces, session tokens and password-reset codes come from secrets (or os.urandom). random is for simulations and games only (randomness and entropy).

Encoding is not cryptography

Python
import base64, binascii

base64.b64encode(b"hi")        # b'aGk='   reversible by anyone
binascii.hexlify(b"hi")        # b'6869'   reversible by anyone

Base64 and hex change the representation, not the secrecy. Classical ciphers (Caesar, Vigenere, substitution) fall to frequency analysis and brute force (classical ciphers).

Do and don't

Do Don't
Use a vetted library and a high-level API Invent your own cipher or protocol
Use AEAD with a unique nonce per message Use ECB, or reuse a nonce or one-time pad
Hash passwords with a salted, slow KDF Store passwords with MD5, SHA-1 or a bare SHA-256
Compare secrets with hmac.compare_digest Compare tags or tokens with ==
Generate secrets with secrets Use random, timestamps or counters as keys
Derive separate keys with HKDF labels Use one key for encryption and MAC
Rotate keys and keep them out of source code Hardcode keys or commit them to Git
Authenticate public keys (certificates, fingerprints) Trust an unauthenticated key exchange
Use padding schemes (OAEP, PSS) with RSA Use textbook RSA
Plan for algorithm change (crypto agility) Assume today's parameters last forever

More on these traps: hash attacks, RSA pitfalls and modes of operation.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You need to detect tampering with a message when sender and receiver share a secret key. What fits best?

    A plain hash can be recomputed by an attacker, and encoding or ECB give no authentication. HMAC needs the secret key, so only key holders can produce a valid tag.
  2. 2. Which source should provide an encryption key?

    Keys need unpredictable bytes from a cryptographically secure generator. The secrets module reads the operating system's CSPRNG; the other choices are guessable.
  3. 3. What is the safest way to compare a received MAC tag with the expected one?

    A normal comparison can stop at the first differing byte, which leaks timing information. compare_digest takes the same time wherever the difference is.
  4. 4. A server stores user passwords. Which choice is best?

    Password storage needs a slow, salted, memory-hard function so that each guess is costly. Fast hashes can be guessed billions of times per second, and reversible encryption exposes every password if the key leaks.

Summary

  • Pick the primitive from the goal: AEAD for secrecy, HMAC or signatures for authenticity, hashes for fingerprints, KDFs for passwords and key derivation.
  • Use secrets for every key, salt, nonce and token. random is never for security.
  • Use AES-GCM or ChaCha20-Poly1305 with a unique nonce per message, and never ECB or unauthenticated modes.
  • Prefer X25519 and Ed25519 today, and remember that RSA needs OAEP or PSS padding.
  • Compare secrets with hmac.compare_digest, store passwords with scrypt, Argon2id or PBKDF2 and a random salt.
  • Use libraries for real systems, and keep key management and rotation in your plan.

You have reached the end of the reference pages. Review the traps once more in hash attacks, or start again with What Is Cryptography?.