我正在使用 Python 3.6 中的 Pycryptodome 开发一个加密程序我试图加密一个文件,然后解密它并验证 MAC 标签。当我验证它时,会引发错误
import os
from Crypto.Cipher import AES
进口围兜 Cryptodome
aad = b'any thing'
nonce = b'\xde\xe2G\xca\xe8Lq9\xeb\x8b\x84\xe7'
key = b'\xde\xe9\xad\xe9\x14_\x07\x1aq7C\\\xd7\x9c\xae\xfcJ\x1c%\xec\xe6C\xbe\xf0eO\xfaJ1\x08\x0c\xae'
我将 nonce 和 key 设置为常量,只是为了先开始。然后我将为每个文件使用唯一的 nonce = get_random_bytes(12)。
def encrypt(filename):
chunksize = 64 * 1024
outputFile = "(encrypted)" + filename
filesize = str(os.path.getsize(filename))
cipher = AES.new(key, AES.MODE_GCM, nonce)
cipher.update(aad)
with open(filename, 'rb') as infile:
with open(outputFile, 'wb') as outfile:
outfile.write(filesize.encode('utf-8'))
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += ' '.encode('utf-8') * (16 - (len(chunk) % 16))
ciphertext,sender_tag = cipher.encrypt_and_digest(chunk)
print (sender_tag)
outfile.write(ciphertext)
解密部分使用decrypt_and_verify,因此无需担心哪个先解密或验证
def decrypt(filename,received_tag):
chunksize = 64 * 1024
outputFile = "(clear)"+ filename
cipher = AES.new(key, AES.MODE_GCM, nonce)
cipher.update(aad)
with open(filename, 'rb') as infile:
with open(outputFile, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
clearmessage = cipher.decrypt_and_verify(chunk, b'received_tag')
outfile.write(clearmessage)
outfile.truncate()
def Main():
choice = input("Would you like to (E)ncrypt or (D)ecrypt?: ")
if choice == 'E':
filename = input("File to encrypt: ")
#password = input("Password: ")
encrypt(filename)
print ("Done.")
elif choice == 'D':
filename = input("File to decrypt: ")
#password = input("Password: ")
received_tag = input("enter received tag:")
decrypt(filename,received_tag)
print ("Done.")
else:
print ("No Option selected, closing...")
if __name__ == '__main__':
Main()
这是错误:
raise ValueError("MAC check failed")
ValueError: MAC check failed
我不知道我在哪里搞砸了。顺便说一句,我得到一个类似于 b'\x1c\xd1\xd8\x1a6\x07\xf3G\x8c_s\x94"*(b'
更新:我确实纠正了代码中的错误 sender_tag,ciphertext = cipher.encrypt_and_digest(chunk) insted of ciphertext,sender_tag = cipher.encrypt_and_digest(chunk) 但问题仍然存在