如何在python中加密JSON
Posted
技术标签:
【中文标题】如何在python中加密JSON【英文标题】:How to encrypt JSON in python 【发布时间】:2020-08-19 18:33:00 【问题描述】:我有一个 JSON 文件。我在 python 中运行一个程序,从 JSON 文件中提取数据。有没有办法用密钥加密 JSON 文件,这样如果有人随机打开文件,就会出现一堆乱七八糟的字符,但是当将密钥提供给程序时,它会对其进行解密并能够读取它?提前致谢。
【问题讨论】:
检查***.com/questions/15973358/… 【参考方案1】:是的,您可以加密 .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()
没有必要。这只是一种将生成的密钥存储在安全位置并重新读取的方法。您可以根据需要删除该块。
如果您需要进一步的帮助,请告诉我:)
【讨论】:
谢谢!我不知道你可以使用 Fernet Keys 加密 JSON 文件!以上是关于如何在python中加密JSON的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Python 中解密 OpenSSL AES 加密的文件?