【发布时间】:2019-12-15 23:10:16
【问题描述】:
我正在尝试使用AES-256 加密一些JSON 数据,使用以pbkdf2_sha256 作为密钥的密码。我想将数据存储在一个文件中,能够加载、解密、更改、加密、存储和重复。
我将passlib 和pycryptodome 库与python 3.8 一起使用。以下测试发生在 docker 容器内并引发我无法纠正的错误
有没有人知道如何改进我的代码(和知识)?
Test.py:
import os, json
from Crypto.PublicKey import RSA
from Crypto.Cipher import AES
from passlib.hash import pbkdf2_sha256
def setJsonData(jsonData, jsonFileName):
with open(jsonFileName, 'wb') as jsonFile:
password = 'd'
key = pbkdf2_sha256.hash(password)[-16:]
data = json.dumps(jsonData).encode("utf8")
cipher = AES.new(key.encode("utf8"), AES.MODE_EAX)
ciphertext, tag = cipher.encrypt_and_digest(data)
[ jsonFile.write(x) for x in (cipher.nonce, tag, ciphertext) ]
def getJsonData(jsonFileName):
with open(jsonFileName, 'rb') as jsonFile:
password = 'd'
key = pbkdf2_sha256.hash(password)[-16:]
nonce, tag, ciphertext = [ jsonFile.read(x) for x in (16, 16, -1) ]
cipher = AES.new(key.encode("utf8"), AES.MODE_EAX, nonce)
data = cipher.decrypt_and_verify(ciphertext, tag)
return json.loads(data)
dictTest = {}
dictTest['test'] = 1
print(str(dictTest))
setJsonData(dictTest, "test")
dictTest = getJsonData("test")
print(str(dictTest))
输出:
{'test': 1}
Traceback (most recent call last):
File "test.py", line 37, in <module>
dictTest = getJsonData("test")
File "test.py", line 24, in getJsonData
data = cipher.decrypt_and_verify(ciphertext, tag)
File "/usr/local/lib/python3.8/site-packages/Crypto/Cipher/_mode_eax.py", line 368, in decrypt_and_verify
self.verify(received_mac_tag)
File "/usr/local/lib/python3.8/site-packages/Crypto/Cipher/_mode_eax.py", line 309, in verify
raise ValueError("MAC check failed")
ValueError: MAC check failed
研究:
-
查看了this 的答案,但我相信我的
verify()电话在 正确的地方 -
我注意到在 python 文档中,它说:
loads(dumps(x)) != x 如果 x 有非字符串键。
但是,当我使用
dictTest['test'] = 'a'重新运行测试时,我遇到了同样的错误。 -
我怀疑问题出在 json 格式上,所以我用一个字符串做了同样的测试,没有调用
json.loads和json.dumps,但我遇到了同样的错误
【问题讨论】:
标签: json python-3.x pycryptodome passlib