我正在尝试使用散列密码作为密钥来加密一些JSON
数据。我想将数据存储在一个文件中,能够加载、解密、更改、加密、存储和重复。AES-256
pbkdf2_sha256
我正在使用passlib
和pycryptodome
库python 3.8
。以下测试发生在 docker 容器内并引发我无法纠正的错误
有没有人知道如何改进我的代码(和知识)?
测试.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
研究:
调查了这个答案,但我相信我的
verify()
电话是在正确的地方我注意到在 python 文档中,它说:
load(dumps(x)) != x 如果 x 有非字符串键。
但是,当我重新运行测试时,
dictTest['test'] = 'a'
我遇到了同样的错误。我怀疑问题出在 json 格式上,所以我用一个字符串做了同样的测试,没有进行
json.loads
andjson.dumps
调用,但我有同样的错误