[python]Sample encrypting and decrypting the dictionary

I am preparing for a credential in dictionary data type to be used in later projects, the entire credential has to be encrypted including username.

First I generate the key for the Fernet cipher, then I get the credential if the creds.enc file is not present.

The obtained credential is updated in the credential dictionary.

I used the json module to translate the dictionary into a string, then convert the string into bytes by encoding it with utf-8.

Then i used the cipher to encrypt the entire credential.

If the creds.enc file exists then I will decrypt the contents.

Below is the example code.

from getpass import getpass
from cryptography.fernet import Fernet
from os.path import exists
import json

credential = {
    "username": None,
    "password": None

key = Fernet.generate_key()
cipher = Fernet(key)

def get_credential():
    username = input("Username: ")
    password = getpass()
    return username, password

if not exists("creds.enc"):
    credential['username'], credential['password'] = get_credential()
    credential_byte = json.dumps(credential).encode('utf-8')
    cred_enc = cipher.encrypt(credential_byte)
    with open("creds.enc", "wb") as file_enc:

with open("creds.enc", "rb")as file_dec:
    cred_decrypt = file_dec.read()
data = cipher.decrypt(cred_decrypt).decode('utf-8')

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s