Cryptography Using Python Modules

Ever wondered how your passwords are hidden? Have you thought about what the word end-to-end encryption in WhatsApp means? Did your curiosity flick, thinking about the process of online money transfer? 

This feat of internet privacy and security is achieved using cryptography, which is a concept for your online protection.

What is Cryptography?

Cryptography is a lock-and-key technique that enables secure communication of information through codes that can only be accessed by the appropriate receiver. The data is encrypted and decrypted to achieve the required confidentiality of the information.

Encryption is basically a conversion of plain text into cipher text. Decryption is the process of retrieving the plain text from the cipher text using a secret key.

Types of Cryptography

There are three widely used types of cryptography:

Type of Cryptography Description
Symmetric Key CryptographyIt is an encryption system where the encrypting and decrypting of the messages are done using a single common key. This system is faster and simpler, but the key has to be shared in a secure manner.
Hash FunctionsA compressed fixed length notation of the message known as the hash value is generated instead of the key. Many operating systems use hash functions to encrypt passwords, as they are completely shielded from other users.
Asymmetric Key CryptographyA pair of unique keys, a Public key – to encrypt and a Private key – to decrypt the messages, are used in this system. 
Table: Types of Cryptography

Python Modules for Cryptography

Modules are files that contain Python statements and definitions for functions, classes, and variables that can be used in your program. It essentially makes the code understandable and logically organized.

In this article, we will shed light on some modules that can be used for the encryption and decryption of data.

1. Fernet Module

The Fernet module comes under the cryptography package. Here, a unique key is generated without which the data cannot be read/modified. Hence it implements Symmetric Key Cryptography.

It uses three major methods to generate keys, encrypt and decrypt the data.

MethodUse CaseSyntax
generate_key()This method is used to generate a new key.key = Fernet.generate_key()
f = Fernet(key)
encrypt(data)The data is encrypted into ciphertext as a “Fernet token” which is in bytes. The parameter is the plain text.encrypted_data = f.encrypt(b”data to be encrypted”)
decrypt(encrypted_data)This method retrieves the original plain text from the Fernet Token.decrypted_data = f.decrypt(encrypted_data)
Table: Methods in Python Fernet Module for Cryptography

To use the Fernet module, you need to install the cryptography package first by running the following command:

pip install cryptography

Now let’s see an example of implementing cryptography in Python using the Fernet module.

# Importing Fernet module from the cryptography package
from cryptography.fernet import Fernet

# Generating a key
key = Fernet.generate_key()

# Assigning the value of key to a variable
f = Fernet(key)

# Converting the plaintext to ciphertext
plainText = input("Enter your text to be encrypted: ").encode()
encryptedData = f.encrypt(plainText)

# Displaying the ciphertext
print("The encrypted data is: ", encryptedData)

# Decrypting the ciphertext
decryptedData = f.decrypt(encryptedData)

# Printing the decrypted data by converting it from byte to string
print("The decrypted data is: ", decryptedData.decode())

As you see, first, the module is imported from the package. Then the fernet key is generated and stored in a variable f. The user inputs the plain text, and it is encrypted. When called, it returns an encrypted cipher text.

The cipher text is later decrypted and printed as a string where the decode function converts the decrypted text from byte to a string.


cryptography using the fernet module of Python

To learn more about Fernet, you can check this article on A Deep Dive Into Fernet Module in Python.

2. Crytocode Module

Cryptocode is a library, which is basically a collection of modules. It is the simplest way of encryption and decryption as it is more suitable for people wanting a mere abstraction.

The encryption has two parameters – the string to be encoded and the key to decrypt the encoded string. This library is not a built-in module, so it needs to be installed in your terminal using the command:

pip install cryptocode

Let’s see an example of implementing cryptography in Python using the Cryptocode module.

# Importing the cryptocode module
import cryptocode
# Entering the string data and password
plainText = input("Enter the text: ")
password = input("Enter the password: ")
# Encrypting the plain text with the password
encryptedData = cryptocode.encrypt(plainText , password)
# Displaying the ciphertext
print("Encrypted data: ",encryptedData)
# Decrypting the ciphertext
decryptedData = cryptocode.decrypt(encryptedData, password)
# Displaying the decrypted data
print("Decrypted data: ",decryptedData)

The module is first imported, and the plainText and password strings are entered. The first parameter in cryptocode.encrypt is a string that will be encrypted into a cipher text, and the latter is the key to decrypt it. 

The cipher text is decrypted using the password, and the plain text is displayed. If the password turns out incorrect, the system throws an error. 


Cryptography using cryptocode module in Python

3. RSA Algorithms

RSA algorithm implements Asymmetric Key Cryptography. It uses two keys for encryption and decryption of text – a public and a private key.

Anyone with a public key can encrypt and send the data. But only the user with the private key can decrypt and access the data.

To install the RSA library, enter the following code in your terminal:

pip install rsa

Let’s see an example code for using RSA algorithms.

# Importing rsa
import rsa

# Generating public and private keys
public_key, private_key = rsa.newkeys(512)
# Reading the plain text
plainText = input("Enter the plain text to be encrypted: ")
# Encrypting the plain text using the public key
encryptedData = rsa.encrypt(plainText.encode(),public_key)
# Decrypting the cipher text using the private key
decryptedData = rsa.decrypt(encryptedData, private_key).decode()
# Displaying the plain text, encoded cipher text and decoded plain text
print("The primordial string: ", plainText)
print("The Encrypted message: ", encryptedData)  
print("The Decrypted message: ", decryptedData)

In the code given above, we import the rsa library and generate the public and private keys. The user inputs plain text. It is then encrypted into a cipher text using the public key. 

The private key is used to decrypt the cipher text into plain text, and all the attributes are displayed.


Cryptography using rsa algorithms in Python

4. Hashlib Modules

Hashlib module is a collection of hashing algorithms used to encrypt data as a hash. Regardless of the size of the data, a hash is a string of fixed length.

This encoding technique is used widely by tech giants as the data encrypted is almost impossible to decrypt. This is a built-in module in Python, so you don’t need to install it. Out of the numerous algorithms present under hashlib, we will take a glance at the SHA256 algorithm.


SHA256 – Secure Hash Algorithm converts the data into a fixed string of 256 bytes in length. It improves security, as longer hashes lead to higher security levels. It is the successor of SHA1 algorithms.

Now let’s see an example code.

# Importing the hashlib module
import hashlib 
# Reading the text to be encoded
plainText = input("Enter the text to be encrypted: ").encode()
# Hashing and encrypting the text
encryptedData = hashlib.sha256(plainText)
# Converting the encrypted text into a hexadecimal
converted = encryptedData.hexdigest()

The module hashlib is imported. The text is entered, and it is converted into bytes using the function encode(). Then the text is hashed and encrypted. Finally, it is converted into a hexadecimal string and displayed. 


Cryptography using hashlib modules (SHA256) in Python

5. AES Algorithms

AES Algorithm uses a single common secret key to encrypt and decrypt the data and is used by governments due to its high level of data integrity. The encryption and decryption occur in blocks where the data is modified and stored in blocks of size 128 bits, whereas the size of the encryption key can be 128, 192, or 256 bits.

Different modes are applied to facilitate a proper stream of data in the blocks. The five modes are:

  • ECB mode: Electronic Code Book mode
  • CBC mode: Cipher Block Chaining mode
  • CFB mode: Cipher Feedback mode
  • OFB mode: Output FeedBack mode
  • CTR mode: Counter mode

Run the following code in your terminal to install the pyaes module:

pip install pyaes

Let’s see an example code:

# Importing the module pyaes
import pyaes
# The key and text are entered and are encoded
key = input("Enter a key of 32 bits: ").encode('utf-8')
plainText = input("Enter the text to be encrypted: ").encode('utf-8')
# AES is constructed using counter mode with key as parameter
aes = pyaes.AESModeOfOperationCTR(key)
# Encrypting the plain text
encryptedData = aes.encrypt(plainText)
# Decrypting the encrypted text as plain text
aes = pyaes.AESModeOfOperationCTR(key)
decryptedData = aes.decrypt(encryptedData)
# Displaying the plain text

The pyaes module is imported. The key and text are entered and encoded into bytes. The key should be 32 bytes(256 bits), or else, an error will be thrown.

AES is constructed using the counter mode as the parameter, and the text is encrypted. Decryption requires a new instance to be created as the counter mode of operation maintains its state. Finally, the text is decrypted and displayed as plain text.


Cryptography using AES algorithms in Python

6. Simple-crypt Module

Simple-crypt justifies its name by portraying it as one of the fastest and simplest ways to encrypt and decrypt text with just a single line of code. It also uses the pycrypto module, which provides the necessary algorithm implementations and a check to warn when cipher text is modified. 

Enter the following command in your terminal to install the modules:

pip install simple-crypt --no-dependencies
pip install pycrypto

Let’s have a look at an example code.

# Importing encrypt and decrypt from simple-crypt
from simplecrypt import encrypt, decrypt
# Entering the key and plain text
key = input("Enter the key: ")
plainText = input("Enter the plain text: ")
# Encrypting the plain text
encryptedData = encrypt(key, plainText)
# Displaying the cipher text
print("Encrypted data: ",encryptedData)
# Decrypting the cipher text and display it
print("Encrypted data: ",decrypt(key, encryptedData))


Cryptography using simple-crypt module in Python

Final Thoughts

Cryptography is a vast ocean that needs more exploration. I have brushed the working of some famous Python modules used in cryptography. Each module has a unique characteristic that has to be implemented in apt situations where they can be efficiently used.

I hope you learned something new about the cryptography modules used in Python. All the best for your future endeavors!

Ashwin Joy

I'm the face behind Pythonista Planet. I learned my first programming language back in 2015. Ever since then, I've been learning programming and immersing myself in technology. On this site, I share everything that I've learned about computer programming.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts