使用 pycrypto 进行非对称 RSA 加密

非对称加密的优点是可以加密消息而无需与消息的接收者交换密钥。发件人只需要知道收件人公钥,这允许加密邮件,使得只有指定的收件人(具有相应的私钥)才能解密它。目前,此功能需要第三方模块,如 pycrypto

from Crypto.Cipher import PKCS1_OAEP
from Crypto.PublicKey import RSA

message = b'This is a very secret message.'

with open('pubkey.pem', 'rb') as f:
    key = RSA.importKey(f.read())
cipher = PKCS1_OAEP.new(key)
encrypted = cipher.encrypt(message)

如果收件人拥有正确的私钥,则可以解密该邮件:

with open('privkey.pem', 'rb') as f:
    key = RSA.importKey(f.read())
cipher = PKCS1_OAEP.new(key)
decrypted = cipher.decrypt(encrypted)

注意 :以上示例使用 PKCS#1 OAEP 加密方案。pycrypto 还实现了 PKCS#1 v1.5 加密方案,但由于已知的注意事项, 不建议将此方案用于新协议。