我想加密和解密大文件。我的策略是在下面编写seal
和open_seal
以将数据加密(作为单字节数组)。对于大文件,每次调用这些函数对读取的数据块进行加密(解密)时,我将逐块读取文件。
该程序在完成1个完整块时起作用。对于大文件,我将调用dark
进行加密,方法是在读取流的每个块上调用seal
。为了解密,我调用light,
,它调用open_seal
来解密每个加密块。加密没有返回任何问题,但是解密失败并显示MAC检查错误。
def seal(self,data):
dataout = bytearray()
session_key = get_random_bytes(16)
# Encrypt the session key with the public RSA key
cipher_rsa = PKCS1_OAEP.new(self.recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)
# Encrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(data)
for x in (enc_session_key, cipher_aes.nonce, tag, ciphertext):
dataout += x
return bytes(dataout)
def open_seal(self,data):
#raise Exception if private_key empty
#private_key = RSA.import_key(khandle)
#private_key = RSA.import_key(private_key)
def split_data(chunks):
i = 0
for x in chunks:
i += x
yield data[i-x:i]
enc_session_key, nonce, tag, ciphertext = \
[x for x in split_data((self.private_key.size_in_bytes(),16,16,len(data)))]
# Decrypt the session key with the private RSA key
cipher_rsa = PKCS1_OAEP.new(self.private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
# Decrypt the data with the AES session key
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
plaindata = cipher_aes.decrypt_and_verify(ciphertext, tag)
return plaindata
#below is in the child class, hence calling super()
def dark(self):
while True:
data_plain = self.stream.read(deadStream.CHUNK)
if data_plain:
data_encrypted = super().seal(data_plain)
yield data_encrypted
else:
break
def light(self):
while True:
data_encrypted = self.stream.read(deadStream.CHUNK)
if data_encrypted:
data_plain = super().open_seal(data_encrypted)
yield data_plain
else:
break
我希望输出将拼接每个解密的块