PyCryptodome Error: MAC Check Failed

PyCryptodome Error: MAC Check Failed

我正在 Python 中使用 Pycryptodome 开发一个加密程序。我正在尝试加密一个(字节)字符串,然后对其进行解密并验证 MAC 标记。当我去验证它时,抛出一个错误。

这是代码:

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes

aes_key = get_random_bytes(24)
aes_cipher = AES.new(aes_key, AES.MODE_GCM)
encrypted, MACtag = aes_cipher.encrypt_and_digest(b"A random thirty two byte string.")

# Imagine this is happening somewhere else
new_aes_cipher = AES.new(aes_key, AES.MODE_GCM, nonce=aes_cipher.nonce)
new_aes_cipher.verify(MACtag)
decrypted = new_aes_cipher.decrypt(encrypted)

这是错误:

Traceback (most recent call last):
  File "aespractice.py", line 10, in <module>
    new_aes_cipher.verify(tag)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-
packages/Crypto/Cipher/_mode_gcm.py", line 441, in verify
    raise ValueError("MAC check failed")
ValueError: MAC check failed

我查看了文档,在我看来一切正常。为什么您认为该程序会以这种方式运行?任何帮助将不胜感激。

如果您查看身份验证模式的状态图:

你看到 verify() 应该在最后调用,在任何 decrypt() 发生之后。 因此,要么反转调用,要么用组合 decrypt_and_verify().

替换它们