Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python中加密JSON,使用加密时出错_Python_Json_Cryptography - Fatal编程技术网

如何在python中加密JSON,使用加密时出错

如何在python中加密JSON,使用加密时出错,python,json,cryptography,Python,Json,Cryptography,这个问题已经在这里得到了回答: 但是,我在使用加密模块时遇到了一个错误 raise TypeError("{} must be bytes".format(name)) TypeError: data must be bytes 这是我的密码: from cryptography.fernet import Fernet key= b'F9tdtAlS5kqVL5_uxKCnOPailXUqKsJmxbHWGLv_H-c=' with open('info.jso

这个问题已经在这里得到了回答:

但是,我在使用加密模块时遇到了一个错误

raise TypeError("{} must be bytes".format(name))
   TypeError: data must be bytes
这是我的密码:

from cryptography.fernet import Fernet
key= b'F9tdtAlS5kqVL5_uxKCnOPailXUqKsJmxbHWGLv_H-c='

with open('info.json', 'rb') as loader1:
    params = json.load(loader1)

if xyz(x, y)==True:

        fernet = Fernet(key)
        encrypted=fernet.encrypt(params)
        print(encrypted)
        with open('info.json', 'wb') as writer1:
            json.dump(encrypted, writer1)
        
        print("Operation was a success")
else:
     print("error")

如果您在原始答案中看到,他们正在从json文件读取内容,而不是使用json.load,因此他们加密的内容是字节格式的,但是您输入的是json,因此错误数据必须是字节。快速修复方法是使用
json.loads
将json转换为字符串,然后编码为字节格式,然后将其输入到fernet.encrypt()中

编码成字节

json.loads()
返回一个字符串,字符串也不是字节对象。为此,只需将其编码为字节或使用类似的字节方法即可