1. RSA加密解密key可以由generate生成,或者由construct構造,或者由importkey導入;
2. RSA可以加密的單段數據長度受key的長度所限制,大量數據需分段加密;
3. 目前推薦使用PKCS1_OAEP加密,PKCS1_V1_5可用於兼容老代碼,但已不推薦使用;
4. 根據RFC 3447描述,若使用PKCS1_OAEP加密,單段數據最大長度爲下圖紅框標識。
例如,若使用RSA 2048,則k = 2048 / 8 = 256,hLen爲使用的hash算法所輸出的字節數,若未指定,則默認爲SHA1,佔用20個字節。因此,最終所能夠加密的明文的最大長度mLen <= 256 - 2*20 - 2 = 214.
若採用RSA 1024,則該長度爲 128 - 42 = 86.
若採用PKCS1_V1_5加密,則能夠加密的明文最大長度爲 k-11。
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
key = RSA.generate(2048)
print 'key: ', key
publickey = key.publickey()
print 'publickey: ', publickey
msg = 'encrypt this message'
print 'orginal data: ', msg
cipher = PKCS1_OAEP.new(key)
encrypted = cipher.encrypt(msg)
print 'encrypted data: ', encrypted
decrypted = cipher.decrypt(encrypted)
print 'decrypted data: ', decrypted
參考:
https://www.dlitz.net/software/pycrypto/api/current/Crypto.Cipher.PKCS1_OAEP-module.html
http://www.rfc-editor.org/pdfrfc/rfc3447.txt.pdf
http://www.emc.com/emc-plus/rsa-labs/standards-initiatives/pkcs-rsa-cryptography-standard.htm