使用 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 加密方案,但由於已知的注意事項, 不建議將此方案用於新協議。