python 3 中如何对大数据进行RSA编码
How to RSA encode large data in python 3
我尝试使用 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')
这不是原始问题的确切答案,但这解决了我的问题:
基于 https://security.stackexchange.com/a/10953
... public-key cryptography is expensive for large messages; the public key algorithm is only used to encrypt the symmetric key and to sign a digest of the file.
所以不建议使用RSA加密大data/files。改为使用 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'
我尝试使用 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')
这不是原始问题的确切答案,但这解决了我的问题: 基于 https://security.stackexchange.com/a/10953
... public-key cryptography is expensive for large messages; the public key algorithm is only used to encrypt the symmetric key and to sign a digest of the file.
所以不建议使用RSA加密大data/files。改为使用 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'