Hashing vs encryption
The most common beginner mistake is picking the wrong primitive. This lesson makes the choice automatic.
In this lesson
- Choose between hashing and encryption for a given requirement
- Explain why passwords are hashed, not encrypted
- Recognise MD5/SHA-1 usage as a security finding
Two questions decide it
Ask: 1) Does the reader need the original data back? If yes → encryption. If no → hashing. 2) Do you need to prove who produced it? If yes → you also need a signature or an HMAC.
- Purpose: integrity / fingerprint
- Any size in, fixed size out
- No key (or HMAC key)
- One-way — cannot be reversed
- SHA-256, SHA-3, BLAKE3
- Purpose: confidentiality
- Same size out as in (roughly)
- Always a key
- Reversible with the key
- AES-GCM, ChaCha20-Poly1305
Example · Passwords: hashed, slowly
Your password is never stored in a database — the server stores a password hash (Argon2, bcrypt, scrypt). These are deliberately slow and memory-hard so that stolen databases cannot be brute-forced at GPU speed. Encrypting passwords would be worse: the key would live next to the ciphertext.
import bcrypt\n\npassword = b"hunter2"\nhashpw = bcrypt.hashpw(password, bcrypt.gensalt(rounds=12))\n\nbcrypt.checkpw(password, hashpw) # True\n# the original password cannot be recovered from hashpw
Red flags in a code review
MD5/SHA-1 for signatures or passwords, "encryption" whose key sits in the same file, base64 called "encryption", or a home-grown cipher. Any of these deserves a finding.
Fingerprint a file
Hash a file before and after a change — the digest flips completely, which is exactly what integrity checking detects.
Decrypt a SHA-256 hash?
Practice · server-gradedCan I encrypt and then hash?
Yes — publishing <code>H(ciphertext)</code> lets anyone verify a message came from you only if the hash is secret (that is essentially HMAC). For public integrity, sign the hash instead.
What about HMAC?
HMAC(key, message) combines a hash with a secret key to authenticate messages — used for API signatures, cookies and session tokens.