Search code examples
pythonjsonencryptiondata-security

How to encrypt JSON in python


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.


Solution

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

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

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

    Note that this block:

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

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