Asymmetric encryption
用两把钥匙,而非一把
- 对称加密有个难题:你必须先想办法共享那把密钥。
- 非对称加密使用一对钥匙:一把公钥和一把私钥。
“挂锁”的思路
- 你的公钥就像一把敞开的挂锁,你把它发给所有人。
- 任何人都能用它把消息锁上 —— 但只有你的私钥能打开它。
- 于是别人可以安全地给你发秘密,而从不需要共享一把密钥。这正是突破所在。
一个微型 RSA
- RSA 是真正的非对称加密。用很小的数字,你就能看到它运转:
n, e, d = 33, 3, 7 # public key (e, n), private key (d, n)
cipher = (7 ** e) % n # lock 7 with the public key
print((cipher ** d) % n) # unlock with the private key -> 7
- 加密和解密用的是不同的钥匙,消息却能完好还原。
你每天都在用它
- 它反过来用,还能实现数字签名(后面几课会讲)。
- 每次看到 HTTPS 时,公钥技术都在后台默默建立安全连接:验证网站身份并协商共享密钥,随后通过高速对称加密传输数据。
涵盖:IGCSE 2.3(非对称、公钥 / 私钥)、A-Level 17.1、AP CSP。
常见错误
- 公钥加密;只有配对的私钥能解密。
- 绝不要分享私钥。
Public & private keys
Anyone encrypts with your public key; only your private key decrypts.
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Here is a tiny RSA with public key (e, n) and private key (d, n). Encrypt message with the public key (cipher = message**e % n), then decrypt with the private key (plain = cipher**d % n). Print plain — it should return to the original.
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
The same keys also work in reverse — that is a digital signature. Sign with the private key (sig = message**d % n), then let anyone verify with the public key (sig**e % n). Print whether the verified value equals message.
点击“运行”查看此处输出。
难度 4/5 · 今日首次完成可获 280 金币及少量额外奖励
Write encrypt(m) with the public key and decrypt(c) with the private key, using n, e, d = 33, 3, 7 (c = m ** e % n, m = c ** d % n). Every message from 2 to 32 must come back unchanged.
点击“运行”查看此处输出。