MITB Banner

Implementing Encryption and Decryption of Data in Python

Securing Data by Implementing Encryption and Decryption of Data in Python

Cryptography is a process which is mainly used for safe and secure communication. It works on different mathematical concepts and algorithms to transfer the encoded data into a secret code which is difficult to decode.  It involves the process of encrypting and decrypting the data, for eg. If I need to send my personal details to someone over mail, I can convert the information using Encryption techniques and send it, on the other hand, the receiver will decrypt the information received using Decryption Techniques and there will be no data tampering in between.

The ciphertext is a data or text which is encrypted into a secret code using a mathematical algorithm, it can be deciphered using different mathematical Algorithms. Encryption is converting the text into a secret message, technically known as converting the plaintext to ciphertext and Decryption is converting the ciphertext back to plaintext so that only the authorized users can decipher and use the data. Generally, it uses a key that is known to both the sender and the receiver so that they can cipher and decipher the text.   

Python has the following  modules/libraries which are used for cryptography namely:

  • Cryptography
  • Simple-Crypt
  • Hashlib:  MD5 & SHA1(Most secured)

In this article, we will be exploring:

  1. Encryption of Data
  2. Decryption of Data
  3. Libraries used for Cryptography

1. Cryptography

Cryptography is a python package that is helpful in Encrypting and Decrypting the data in python. It provides cryptographic recipes to python developers.

Let us explore Cryptography and see how to encrypt and decrypt data using it. 

Implementation:

We first need to install the library using pip install cryptography.

a. Importing the library

Fernet function is used for encryption and decryption in Cryptography. Let us import the Fernet function from the library.

from cryptography.fernet import Fernet

b. Generating the Key

Cryptography works on authentication for which we will need to generate a key. Let’s define a function to generate a key and write it to a file. This function will create a key file where our generated key will be stored.

# Generating the key and writing it to a file
def genwrite_key():
    key = Fernet.generate_key()
    with open("pass.key", "wb") as key_file:
        key_file.write(key)

This function will create a pass.key file in your directory as shown in the image below.

Encryption and Decryption in Python

c. Loading the Key

The key generated above is a unique key and it will be used further for all encryption and decryption processes so In order to call this key, again and again, let us define a function to load the key whenever required. 

# Function to load the key
def call_key():
                  return open("pass.key", "rb").read()

d. Encrypting the Data

The next step would be passing the message you want to encrypt in the encode function, initializing the Fernet class, and encrypt the data using encrypt function. 

key = call_key()
slogan = "Hello!! Welcome to AIM!!".encode()
a = Fernet(key)
coded_slogan = a.encrypt(slogan)
print(coded_slogan)
Encryption and Decryption in Python

As you can see we have successfully encrypted the data.

e. Decryption of Data

The message will be decrypted with the same key that we used to encrypt it and by using the function decrypt. Let us decode the encrypted message.

key = call_key()
b = Fernet(key)
decoded_slogan = b.decrypt(coded_slogan)
print(decoded_slogan)


As you can see here we have successfully decoded the message. While using cryptography it is necessary to keep the Key file safe and secure to decode the message because if the Key is misplaced the message/data will not be decoded.

Similarly, Cryptography module can be used to convert data/text files, we just need to pass the file to the argument and encode and decode it.

2. Simple Crypt

It is a python module which is fast and converts the plaintext to ciphertext and ciphertext to plain text in seconds and with just a single line of code. 

Implementation:

We first need to install the library using, pip install simple-crypt

a. Loading the Library

from simplecrypt import encrypt, decrypt

b. Encrypting and Decrypting

Simple-crypt has two pre-defined functions encrypt and decrypt which controls the process of encryption and decryption. For encryption, we need to call the encrypt function and pass the key and message to be encrypted. 

message = "Hello!! Welcome to AIM!!"
ciphercode = encrypt('AIM', message)
print(ciphercode)
Encryption and Decryption in Python


Similarly, we can call the decrypt function and decode the original message from this ciphertext.

original = decrypt('AIM', ciphercode)
print(original)


Here you can see that we have used “AIM” as the password and it is the same for encryption and decryption. 

In simple-crypt, we should keep in mind that the same key should be provided for encryption and decryption otherwise messages will not be decoded back to original. 

3. Hashlib

Hashlib is an open-source python library used for encoding and it contains most of the popular hashing algorithms used by big tech firms for security purposes. Hash is a function that takes variable length as an input and gives the fixed-length output sequence. Unlike the modules discussed earlier in Hashlib decoding is a very difficult and time-consuming job this is why Hashing is considered as the most secure and safe encoding.

The Hashlib functions that we will be exploring are MD5 and SHA1

3.1 MD5

MD5 Algorithm/Function produces a hash value which is 128 bit.  It converts the strings to bytes so that it is accepted by hash. MD5 is mainly used for checking Data Integrity. It is predefined in hashlib.

Implementation:

We need to install the hashlib library to use MD5 using, pip install hashlib

a. Importing the library

import hashlib

b. Encrypting the data

In order to encrypt the data, we need to pass the message/data to the MD5 function to convert it into bytes. Here you will see that we will type ‘b’ before typing the message because it converts the string to bytes so that it will be accepted by hash. The hexdigest function will encode the message and return the encoded message as a HEX string.

encoded_message = hashlib.md5(b'Hello!! Welcome to AIM!!')
converted = encoded_message.hexdigest()
print(converted)
Encryption and Decryption in Python

If we do not want the message to be encoded in HEX string and show it in a sequence of bytes then we will use the digest function.




3. 2 SHA1

Secure Hash Algorithms are more secured than MD5. It s a set of the algorithm like SHA1, SHA256, etc. It is widely used for cryptographic applications.

We have already imported the hashlib library so we will directly Encode the message/data using SHA1. 

Encryption of Data 

In order to encrypt the data, we need to pass the message/data to the SHA1 function to convert it into bytes. Similar to MD5 here also you will see that we will type ‘b’ before typing the message because it converts the string to bytes so that it will be accepted by hash. The hexdigest function will encode the message and return the encoded message as a HEX string.

encoded_message = hashlib.sha1(b'Hello!! Welcome to AIM!!')
converted = encoded_message.hexdigest()
print(converted)


Similar to MD5 if we do not want the message to be encoded in HEX string and show it in a sequence of bytes then we will use the digest function.



Similarly, we can try different hashing algorithms for Encoding/Encryption.

Conclusion:

In this article, we went through:

  1.  What is cryptography and how we can use it for encryption and decryption of data/message? 
  2. We learned how simple-crypt makes encryption and decryption an easy task with just one line of code.
  3. We explored the most secure and safe algorithms/functions for encoding message/data and how to implement it.

Access all our open Survey & Awards Nomination forms in one place >>

Picture of Himanshu Sharma

Himanshu Sharma

An aspiring Data Scientist currently Pursuing MBA in Applied Data Science, with an Interest in the financial markets. I have experience in Data Analytics, Data Visualization, Machine Learning, Creating Dashboards and Writing articles related to Data Science.

Download our Mobile App

CORPORATE TRAINING PROGRAMS ON GENERATIVE AI

Generative AI Skilling for Enterprises

Our customized corporate training program on Generative AI provides a unique opportunity to empower, retain, and advance your talent.

3 Ways to Join our Community

Telegram group

Discover special offers, top stories, upcoming events, and more.

Discord Server

Stay Connected with a larger ecosystem of data science and ML Professionals

Subscribe to our Daily newsletter

Get our daily awesome stories & videos in your inbox
Recent Stories