【发布时间】:2017-03-30 02:04:24
【问题描述】:
我知道 RSA 一次不能加密超过 128 个字节(模数),所以我分块加密和解密文件。但是,如果我的文件大于几 kb,则每次运行程序时结果都会发生变化。有时整个文件被正确加密和解密。有时只有前 100 行等。此时我想知道这是否是 Crypto.PublicKey.RSA 模块的可靠性问题。这是我的代码:
def encrypt(file, public_key):
read_size = 128
with open(file, 'rb') as original_file:
e_file = file + '.e'
with open(e_file, 'wb') as encrypted_file:
while True:
file_part = original_file.read(read_size)
if len(filePart) == 0:
break
encrypted_file.write(public_key.encrypt(file_part, None)[0])
os.remove(file)
def decrypt(file, private_key):
read_size = 128
with open(file, 'rb') as encrypted_file:
d_file = file[:-2]
with open(d_file, 'wb') as decrypted_file:
while True:
file_part = encrypted_file.read(read_size)
if len(filePart) == 0:
break
decrypted_file.write(private_key.decrypt(file_part))
os.remove(file)
private_key = RSA.generate(1024)
public_key = RSA.importKey(private_key.publickey().exportKey())
my_file = 'myfile.txt'
encrypt(my_file, public_key)
decrypt(my_file + '.e', private_key)
编辑:: Maarten 的回答是有效的。这是一个具体的例子,说明我是如何用他的回答解决我的问题的。 我使用了这个导入:
from Crypto.Cipher import PKCS1_OAEP
然后我没有直接使用公钥加密,而是使用了这个:
cipher = PKCS1_OAEP.new(publicKey)
encryptedFile.write(cipher.encrypt(filePart))
然后我做了类似的解密。
【问题讨论】:
-
" 知道 RSA 一次不能加密超过 128 个字节......" 不,它甚至不能加密那么多,即使没有填充。明文,取整数,必须小于模数。根据模数的确切值,可能有很大一部分 128 字节的明文太大。
标签: python python-3.x cryptography rsa pycrypto