python - PyCryptodome 错误 : MAC Check Failed

标签 python encryption cryptography pycrypto pycryptodome

我正在使用 Python 3 中的 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

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

最佳答案

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

enter image description here

您看到 verify() 应该在最后调用,在任何 decrypt() 发生之后。 因此,要么反转调用,要么用组合的 decrypt_and_verify() 替换它们。

关于python - PyCryptodome 错误 : MAC Check Failed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48616390/

相关文章:

Java:解密位置未知的凯撒密码

php - 使用 SJCL 在 Javascript 中加密并在 PHP 中解密

java - 文件的加密/解密操作在 Android 平台上产生奇怪的效果

python3 - 就地编辑 YAML 文件中的值

python - 带有压缩静态文件的 Django Whitenoise

python - 识别所有有问题的引号实例

java - 临时 RSA key 与临时 DH key ?

python - 使用工作流在 github 中对 databricks python 代码进行 flake8 linting

c# - 在 .NET 中加密字符串并在 PHP 中解密?

java - 使用 Bouncy CaSTLe Java API 生成 X.509 证书