您的位置:首页 > 其它

加密解密之RSA

2016-07-01 16:58 627 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: