Module 77: Encryption and Secrets
Hashing vs encryption
🏠The everyday picture
Encryption is a locked box: with the key, you get the contents back. Hashing is a fingerprint: it identifies the person, but you can't rebuild the person from it.
📘What it really is
-
Hashing turns any data into a fixed-length fingerprint (hash). It's one-way: you can't get the original back. The same input always gives the same hash; a tiny change gives a completely different one.
-
Uses:
- file integrity: checking a download matches its published SHA-256 hash;
- Git identifies commits by hash;
- HMAC: a hash combined with a secret key, proving a message wasn't changed and came from someone with the key (webhook signatures, Module 76).
- Passwords need special hashing. Fast hashes (SHA-256) can be tried billions of times a second. Password hashes are slow on purpose and salted (a random value per password, so identical passwords have different hashes):
- Argon2id (recommended), bcrypt, or scrypt;
-
never MD5 or SHA-1 for anything security-related; never plain SHA-256 for passwords.
-
Choosing:
- need the original back later (a bank account number to display)? Encrypt.
- need only to check a value matches (passwords, API keys)? Hash (password hash for passwords; a fast hash of a long random API key is fine, because it can't be guessed).
- Encoding (Base64, URL encoding) isn't security at all; anyone can decode it. JWTs are encoded, not encrypted (Module 74).
- Never invent your own cryptography. Use the standard library (
node:crypto), proven libraries (argon2,bcrypt, libsodium) and well-known settings.
🖱️Try it
In Node.js, hash "hello" and "hello!" with SHA-256 (crypto.createHash("sha256").update(s).digest("hex")) and compare.
Hash the same password twice with bcrypt and notice the results differ (the salt), yet both verify. Time 10 bcrypt hashes at
cost 12 against 10 SHA-256 hashes, and explain why the slow one is right for passwords.
✅Quick check
Why should passwords be hashed rather than encrypted?
Show the answer
You only ever need to check them, never read them back; hashing means even a stolen database doesn't reveal them.
Why are fast hashes like SHA-256 wrong for passwords?
Show the answer
Attackers can try billions of guesses per second; password hashes are deliberately slow and salted.
