PyCryptodome错误:MAC检查失败 [英] PyCryptodome Error: MAC Check Failed

查看:137
本文介绍了PyCryptodome错误:MAC检查失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 3中的Pycryptodome开发一个加密程序,我正在尝试加密(字节)字符串,然后将其解密并验证MAC标签。当我验证它时,会引发错误。

I am working on an encryption program with Pycryptodome in Python 3. I am trying to encrypt a (byte) string and then decrypt it and verify the MAC tag. When I get to verify it, an error is thrown.

这是代码:

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

我看了看文档,对我来说似乎一切都很好。您为什么认为该程序以这种方式运行?任何帮助将不胜感激。

I've looked at the documentation, and I it looks to me like everything is all right. Why do you think the program is acting this way? Any help would be appreciated.

推荐答案

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

If you look at the state diagram for authenticated modes:

您会看到 verify() decrypt()发生之后,应在最后调用c>。
因此,您可以反转呼叫,或者将其替换为组合的 decrypt_and_verify()

You see that verify() should be called at the very end, after any decrypt() has taken place. So, either you invert the calls or you replace them with a combined decrypt_and_verify().

这篇关于PyCryptodome错误:MAC检查失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆