我正在尝试将AES-GCM加密用于python中的文件加密。我正在使用Cryptodome
程序包,并且我确切地知道如何对基于this example的单个纯文本字符串使用encrypt_and_digest
和decrypt_and_verify
进行加密/解密。
现在,我正在尝试加密和解密文本文件。它包含多个AES块,我想在解密过程开始时检查身份验证标签,以验证文件的完整性。我无法弄清楚如何为整个文件生成单个身份验证标签并在目标位置进行验证。目前,我有以下代码:
加密
def encrypt(self, filename):
iv = get_random_bytes(16)
cipher = AES.new(self.K4, AES.MODE_GCM, iv)
try:
with open(filename, 'rb') as src:
with open(filename + ".enc", 'wb') as des:
des.write(iv)
for block in iter(lambda: src.read(AES.block_size * 128), b''):
if len(block) == AES.block_size * 128:
des.write(cipher.encrypt(block))
# Padding the last block
else:
remain = len(block) % 16
if remain == 0:
remain = 16
block += utility.to_bytes((chr(remain) * remain))
des.write(cipher.encrypt(block))
except (IOError, OSError):
raise IOError("Cannot open the file to encrypt")
解密
def decrypt(self, ciphertext):
try:
with open(ciphertext, 'rb') as src:
with open(ciphertext.strip(".enc") + ".dec", 'wb+') as des:
iv = src.read(16)
cipher = AES.new(self.K4, AES.MODE_GCM, iv)
for block in iter(lambda: src.read(AES.block_size * 128), b''):
des.write(cipher.decrypt(block))
# Remove padding
# Set the pos to the beginning of the last byte
des.seek(-1, os.SEEK_END)
# Read the last byte
last = des.read(1)
des.seek(-int.from_bytes(last, byteorder='big'), os.SEEK_END)
des.truncate()
except (IOError, OSError):
raise IOError("Cannot open the file to decrypt")
您可以清楚地看到,没有执行身份验证。任何想法?