Hackernoon logoHow to Encrypt and Decrypt Data in Python by@gajesh2007

How to Encrypt and Decrypt Data in Python

Author profile picture

@gajesh2007Gajesh Naik

I am Gajesh Naik. I am 12 years old. I started programming at the age of 7. I have skilled 9 P. Lang

Are you a Visual Learner? Check out this tutorial on YouTube. Click Here
Encryption is the process of encoding an information in such a way that only authorized parties can access it. It is critically important because it allows you to securely protect data that you don't want anyone to see or access it.
In this tutorial, you will learn how to use Python to encrypt files or any byte object (also string objects) using cryptography library.
We will be using symmetric encryption, which means the same key we used to encrypt data, is also usable for decryption. There are a lot of encryption algorithms out there, the library we gonna use is built on top of AES algorithm.
Note: It is important to understand the difference between encryption and hashing algorithms, in encryption, you can retrieve the original data once you have the key, where in hashing functions, you cannot, that's why they're called one-way encryption.
Let's start off by installing cryptography:
pip3 install cryptography
Open up a new Python file and let's get started:
from cryptography.fernet import Fernet

Generating the Key

Fernet is an implementation of symmetric authenticated cryptography, let's start by generating that key and write it to a file:
def write_key():
    Generates a key and save it into a file
    key = Fernet.generate_key()
    with open("key.key", "wb") as key_file:
generate_key() function generates a fresh fernet key, you really need to keep this in a safe place, if you lose the key, you will no longer be able to decrypt data that was encrypted with this key.
Since this key is unique, we won't be generating the key each time we encrypt anything, so we need a function to load that key for us:
def load_key():
    Loads the key from the current directory named `key.key`
    return open("key.key", "rb").read()

String Encryption

Now that we know how to get the key, let's start by encrypting string objects, just to make you familiar with it first.
Generating and writing the key to a file:
# generate and write a new key
Let's load that key:
# load the previously generated key
key = load_key()
Some message:
message = "some secret message".encode()
We need to encode strings, to convert them to bytes to be suitable for encryption, encode() method encodes that string using utf-8 codec. Initializing the Fernet class with that key:
# initialize the Fernet class
f = Fernet(key)
Encrypting the message:
# encrypt the message
encrypted = f.encrypt(message)
f.encrypt() method encrypts the data passed, the result of this encryption is known as a "Fernet token" and has strong privacy and authenticity guarantees.
Let's see how it looks:
# print how it looks
Decrypting that:
decrypted_encrypted = f.decrypt(encrypted)
b'some secret message'
That's indeed, the same message.
f.decrypt() method decrypts a Fernet token. This will return the original plaintext as the result when it's successfully decrypted, otherwise it'll raise an exception.
Check cryptography's official documentation for further details and instructions.
Also, if you're interested in cryptography, I would personally suggest you read Serious Cryptography book, as it is very suitable for you and not very mathematically detailed.


The Noonification banner

Subscribe to get your daily round-up of top tech stories!