如何在python 3中对大数据进行RSA编码

时间:2017-09-17 14:12:23

标签: python-3.x large-files pycrypto

我尝试使用pycrypto库使用python3.x加密数据。它适用于短数据但不适用于长数组。如何加密长数据?我应该写一个包装器来分割数据较小的块吗?或者是否有其他加密库可以处理长数据?

from Crypto.PublicKey import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
publickey = key.publickey() 

"""
Shorter (128 bytes)
"""
msg = b'abcd'*32
print(msg)          # b'abcdabcdabcd...
enc=publickey.encrypt(msg, 32)
print(enc)          # Depends on key. Ex.: (b"hd\n\xbb\xe4\x8b...
dec=key.decrypt(enc)
print(dec)          # b'abcdabcdabcdabcda...

if msg==dec:        # TRUE
    print('TRUE')
else:
    print('FALSE')

"""
LONGER (132 bytes)
"""
msg = b'abcd'*33
print(msg)          # b'abcdabcdabcd...
enc=publickey.encrypt(msg, 32)
print(enc)          # Depends on key. Ex.: (b'\xa2J1;\xd4`\xc5i\x...   
dec=key.decrypt(enc)
print(dec)          # Depends on key. Ex.: b'|*\xb85\\B\\r2\xea\...   

if msg==dec:        # FALSE
    print('TRUE')
else:
    print('FALSE')

1 个答案:

答案 0 :(得分:0)

这不是原始问题的确切答案,但这解决了我的问题: 基于https://security.stackexchange.com/a/10953

  

...公钥加密对于大型邮件来说是昂贵的;公钥算法仅用于加密对称密钥和签署文件的摘要。

因此不建议使用RSA加密大型数据/文件。请改用AES:

from Crypto.Cipher import AES
obj = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = "The answer is no"*32
ciphertext = obj.encrypt(message)
print(ciphertext)
# '\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
obj2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
print(obj2.decrypt(ciphertext))
# 'The answer is no'