3

我有一个 JSON 文件。我在 python 中运行一个程序,从 JSON 文件中提取数据。有没有办法用密钥加密 JSON 文件,这样如果有人随机打开文件,就会出现一堆乱七八糟的字符,但是当将密钥提供给程序时,它会对其进行解密并能够读取它?提前致谢。

4

1 回答 1

5

是的,您可以加密 .json 文件。确保通过键入来安装加密包

pip install cryptography
# or on windows:
python -m pip install cryptography

然后,您可以制作一个类似于我的程序:

#this imports the cryptography package
from cryptography.fernet import Fernet

#this generates a key and opens a file 'key.key' and writes the key there
key = Fernet.generate_key()
with open('key.key','wb') as file:
    file.write(key)

#this just opens your 'key.key' and assings the key stored there as 'key'
with open('key.key','rb') as file:
    key = file.read()

#this opens your json and reads its data into a new variable called 'data'
with open('filename.json','rb') as f:
    data = f.read()

#this encrypts the data read from your json and stores it in 'encrypted'
fernet = Fernet(key)
encrypted = fernet.encrypt(data)

#this writes your new, encrypted data into a new JSON file
with open('filename.json','wb') as f:
    f.write(encrypted)

请注意,此块:

with open('key.key','wb') as file:
    file.write(key)

#this just opens your 'key.key' and assigns the key stored there as 'key'
with open('key.key','rb') as file:
    key = file.read()

没有必要。这只是一种将生成的密钥存储在安全位置并将其读回的方法。您可以根据需要删除该块。

如果您需要进一步的帮助,请告诉我 :)

于 2020-05-05T07:28:37.073 回答