How to encrypt and decrypt data in Python


Introduction

What is cryptography? Cryptography deals with the conversion of plain text into cipher text which is called encryption of data and cipher text back to plain text which is called decryption of data.

We will be using the fernet module in the cryptography package to encrypt and decrypt data using Python. While using the fernet module, a unique key is generated without which you cannot read or manipulate the encrypted data.

Now that you know what we will be dealing with, let’s get started.

Getting Started

The cryptography module does not come packaged with Python, which means you will have to install it using the pip package manager. To do so, launch your terminal and type in the code below.

pip install cryptography

Once you have the package downloaded and installed, you can import its modules.

We will be using the fernet module to encrypt and decrypt data. So, let us import it into the Python script.

from cryptography.fernet import Fernet

Note − Make sure you get the capitalization’s correct.

You are all set to start writing your script.

Generating a Key

In order to start encrypting data, you must first create a fernet key.

key = Fernet.generate_key()
f = Fernet(key)

In the above lines, we generated a key using the generate_key() method and then assigned that key to a variable “f” in the next line.

And that’s it, you now have a key stored in a variable ready to be used.

We can print the key and store it, if needed. Make sure to use the decode function while printing.

print(key.decode())

Output

Bq64GE−−93K1RVro4go1frN−8twBSvXdbCPSPLIKz9U=

Encrypting Data

In order to encrypt data from the above key, you must use the encrypt method.

encrypted_data = f.encrypt(b"This message is being encrypted and cannot be seen!")

And that’s it, the above sentence has been encrypted.

To view your encrypted message, you must print it.

print(encrypted_data)

Output

b'gAAAAABgILy91p_wqMntdT3mDkh0IBXSLjuBMQAfnGZAFkZCX1U6Q7TU2PthgFBwVz0QbKXpuNTHRzAgbdDV4zfuuzkGCXqVD--xJdkTycKH2iurC_oqHySLc9xJEXz93LkhTbKUa5HCxfJtB-Um_YkxqjclftXXZQ=='

Note − We had the b before the sentence in order to convert it into byte format. You can choose use the encode() method instead as well.

Decrypting Data

Now that you have the cipher text, let us see how we can convert it back to plain readable text.

We can achieve decryption using the decrypt method in the fernet module.

decrypted_data = f.decrypt(encrypted_data) # f is the variable that has the value of the key.
print(decrypted_data)

Output

b'This message is being encrypted and cannot be seen!'

Note − If you look at the above output, you can notice that there is b’ before the printed plaintext, this is because encrypted data is being converted back into byte format. In order to get just the plain text, we need to use the decode function.

print(decrypted_data.decode())

Output

This message is being encrypted and cannot be seen!

Note − You can encrypt and decrypt data using the same key. That is, if you print the value of the key and save it. You can use the same key by assigning it to a variable. Example −>

f = Fernet(Bq64GE--93K1RVro4go1frN-8twBSvXdbCPSPLIKz9U=) # Value of an actual key is given.

Example

from cryptography.fernet import Fernet
key = Fernet.generate_key()
print("Key : ", key.decode())
f = Fernet(key)
encrypted_data = f.encrypt(b"This message is being encrypted and cannot be seen!")
print("After encryption : ", encrypted_data)
decrypted_data = f.decrypt(encrypted_data)
print(decrypted_data)
print("After decryption : ", decrypted_data.decode())

Output

Key : u4dM7xw8sNNU3Rm_lwDbixudWSeaM0Z4TTDdQNKsouI=
After encryption : b'gAAAAABgIL3_qbfM_oMgQn653gpk6a7hqxXiR0dl0vrmOmqnr5b6MqrsjGkK1IknxMLLtOCq6_YlX4x3nBedbZqtCqy4os55pttrl-pBO6-dJf6kVP50IpIaKSXbpAsuWl4h_2o_E-4YEqZ5kkgxWrwnqojmkMyuSQ=='
b'This message is being encrypted and cannot be seen!'
After decryption : This message is being encrypted and cannot be seen!

Conclusion

You have now learnt to encrypt and decrypt data using the cryptography package in Python.

You can even save the key as a .txt file and then retrieve it to encrypt and store password or decrypt password from database to verify if it matches. There are various other cases where you can use this, be it a mini−project or a large scale project.

For more information on the cryptography module, you can read through their official documentation at − https://pypi.org/project/cryptography/

Updated on: 11-Feb-2021

15K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements