Symmetric encryption
用密钥上锁
- 加密把消息打乱,使得只有持有密钥的人才能读懂。
- 在对称加密中,同一把密钥既上锁也解锁。发送方和接收方都必须知道它。
凯撒密码
- 最古老的例子:把每个字母向后移动固定的位数。移动 3 位时,
a → d、b → e,以此类推。 - 密钥就是这个位移量。解密只需反向移动。
text = "attack"
shift = 3
out = "".join(chr((ord(c) - 97 + shift) % 26 + 97) for c in text)
print(out) # dwwdfn
凯撒密码为什么弱
- 一共只有 25 种可能的位移,所以计算机一眨眼就能全部试完。
- 这就是对密钥的暴力破解攻击 —— 而真正的加密必须能抵抗它。
真正的密码做了什么
- 现代对称加密算法如 AES 使用 128-位或更长的密钥:2¹²⁸ 对应约 3 × 10³⁸ 种可能的密钥组合,数量庞大到无法逐一尝试。
- 它们留下的大难题是:两个人如何安全地共享这把密钥? 下一课来解决它。
涵盖:IGCSE 2.3(对称加密)、A-Level 17.1。
常见错误
- 一把共享密钥既加密又解密。
- 难点在于安全地共享这把密钥。
对称加密
The Caesar cipher uses one shared key to encrypt and decrypt.
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Encrypt hello with a Caesar cipher: shift each letter forward by shift places (wrapping past z back to a). Build the encrypted string and print it.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
Now break it — that is why Caesar is weak. You intercepted cipher, and you suspect the plaintext is attack. Try every shift from 1 to 25, shifting 反向, and print the shift that turns cipher 生成 attack.
点击“运行”查看此处输出。
难度 3/5 · 今日首次完成可获 200 金币及少量额外奖励
The receiver knows the key, so they can undo the shift. Write decrypt(text, shift), which moves each lowercase letter 反向 by shift (wrapping from a back to z) and leaves spaces and other characters unchanged.
点击“运行”查看此处输出。