如何在python中加密JSON [英] How to encrypt JSON in python

查看:451
本文介绍了如何在python中加密JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JSON文件.我正在python中运行一个程序,其中数据是从JSON文件中提取的.有什么方法可以用密钥加密JSON文件,以便如果有人随机打开该文件,将是一堆字符,但是当将密钥提供给程序时,它将解密并能够读取它?预先感谢.

I have a JSON file. I am running a program, in python, where data is extracted from the JSON file. Is there any way to encrypt the JSON file with a key, so that if someone randomly opens the file, it would be a mess of characters, but when the key is fed to the program, it decrypts it and is able to read it? Thanks in advance.

推荐答案

是的,您可以加密.json文件.确保通过键入

Yes, you can encrypt a .json file. Make sure you install the cryptography package by typing

pip install cryptography

python -m pip install cryptography

如果您在Windows上.

if you are on windows.

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

Then, you can make a program similar to mine:

#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()
file = open('key.key','wb')
file.write(key)
file.close()

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

#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)

请注意,此代码段:

file = open('key.key','wb')
file.write(key)
file.close()

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

不是必需的.这只是将生成的密钥存储在安全的地方,然后将其读回的一种方法.您可以根据需要删除该块.

isn't necessary. It is just a way to store the generated key in a safe place, and read it back in. You can delete that block if you want.

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

Let me know if you need further assistance :)

这篇关于如何在python中加密JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆