Storing passwords safely
The big rule: never store plain passwords
- If a website stores your password as plain text and gets hacked, every password is stolen instantly.
- Instead, sites store a hash — a scrambled fingerprint that cannot be reversed back into the password.
What is a hash?
- A hash function turns any input into a fixed-length string. The same input always gives the same hash.
- It is one-way: easy to compute forwards, practically impossible to reverse.
- When you log in, the site hashes what you typed and compares it to the stored hash — it only ever stores the hash, never your actual password.
import hashlib
print(hashlib.sha256(b"hello").hexdigest())
Add salt
- If two users pick the same password, their hashes match — a clue for attackers.
- A salt is a random string added before hashing, so identical passwords get different hashes.
- It also defeats pre-computed "rainbow table" attacks. Always salt.
- Salt is not the whole answer. SHA-256 is built to be fast, so an attacker holding stolen hashes can still try billions of guesses a second. Real sites use a deliberately slow password-hashing function: bcrypt, scrypt, Argon2 or PBKDF2. This lesson uses SHA-256 because it shows the idea in one line.
Your turn
- Hash
salt + passwordwith SHA-256. The check confirms you produced the correct 64-character digest.
Covers: A-Level 6.1, 17.1 (encryption/hashing).
Common mistakes
- Never store passwords in plain text.
- Store a salted hash, not the password itself.
- A fast hash such as SHA-256 on its own is too quick to guess against. Real systems use a slow password-hashing function.
Store the hash, not the password
Sites store a hash; a tiny change gives a totally different digest.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Never store a plain password — store its hash. Using hashlib, hash the salt + password with SHA-256 and put the hex digest in a variable called digest.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Now be the login system. The database holds a salt and a stored digest — never the password. Hash salt + attempt with SHA-256 and print welcome if it matches stored, else denied.
Click Run to see the output here.
Difficulty 3/5 · 200 coins + a small bonus on first completion today
Salt makes equal passwords look different. Write hash_password(salt, password), which returns the SHA-256 hex digest of salt + password.
Click Run to see the output here.