JSON和Python加密:TypeError:字节类型的对象不可JSON序列化



我做错了什么?我试图加密用户名和密码,但当我将它们放入json时,我会收到这个错误。欢迎任何帮助!很抱歉给您带来麻烦!Python 3.7.0我不知道加密版本。

def editjson(location, value):
with open("config.json") as f:
data = f.read()
d = json.loads(data)
d[location] = [value]
with open("config.json", 'w') as f:
f.write(json.dumps(d))
def firstruntrue():
key = Fernet.generate_key()
f = Fernet(key)
userog = input("What is your Username? ").encode()
encrypteduser = f.encrypt(userog).decode()
passwordog = input("What is your Password? ").encode()
encryptedpassword = f.encrypt(passwordog).decode()
editjson("firstrun", "False")
editjson("user", encrypteduser)
editjson("password", encryptedpassword)
editjson("key", key)
with open("./config.json", "r") as handler:
info = json.load(handler)
user = info["user"]
password = info["password"]
firstrun = info["firstrun"]
C:UsersUSERDesktopCode>python -u C:UsersUSERDesktopCodeOpenGradebook.py
What is your Username? test
What is your Password? test
Traceback (most recent call last):
File "C:UsersUSERDesktopCodeOpenGradebook.py", line 36, in <module>
firstruntrue()
File "C:UsersUSERDesktopCodeOpenGradebook.py", line 27, in firstruntrue
editjson("key", key)
File "C:UsersUSERDesktopCodeOpenGradebook.py", line 15, in editjson
f.write(json.dumps(d))
File "C:Program FilesPython37libjson__init__.py", line 231, in dumps
return _default_encoder.encode(obj)
File "C:Program FilesPython37libjsonencoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:Program FilesPython37libjsonencoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:Program FilesPython37libjsonencoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type bytes is not JSON serializable

来自密码学文档:

key以字节为单位,并且您正在序列化字节对象editjson("key", key)

尝试更改为editjson("key", key.decode())

最新更新