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