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)**是一段在哈希前加入的随机字符串,让相同的密码得到不同的哈希。
- 它还能挫败预先计算好的“彩虹表”攻击。一定要加盐。
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).
轮到你了
- 对
salt + password做 SHA-256 哈希。检查会确认你算出了正确的 64 位摘要。
涵盖:A-Level 6.1、17.1(加密 / 哈希)。
Common mistakes
- Never store passwords in plain text.
- Store a salted hash, not the password itself.
常见错误
- 绝不要用明文存储密码。
- 存储加盐的哈希,而不是密码本身。
Store the hash, not the password · 存哈希,不存密码
Sites store a hash · 散列值; a tiny change gives a totally different digest. · 网站存的是哈希;一点点改动就得到完全不同的摘要。
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. · 永远不要存储明文密码 —— 要存它的哈希值。用 hashlib,对 salt + password 做 SHA-256 哈希,并把十六进制摘要放进名为 digest 的变量里。
Click Run to see the output here. · 点击“运行”查看此处输出。
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. · 现在扮演登录系统。数据库里存着 salt 和 stored 摘要 —— 从不存密码。对 salt + attempt 做 SHA-256 哈希:与 stored 一致就打印 welcome,否则打印 denied。
Click Run to see the output here. · 点击“运行”查看此处输出。