python json加密,如何在python中加密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.

解决方案

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

pip install cryptography

or

python -m pip install cryptography

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)

Note that this block:

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值