Implementing Encryption and Decryption of Data in Python (2024)

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 filedef 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.

Implementing Encryption and Decryption of Data in Python (1)

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 keydef 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)Implementing Encryption and Decryption of Data in Python (2)

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)Implementing Encryption and Decryption of Data in Python (3)

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)Implementing Encryption and Decryption of Data in Python (4)

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

original = decrypt('AIM', ciphercode)print(original)Implementing Encryption and Decryption of Data in Python (5)

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)Implementing Encryption and Decryption of Data in Python (6)

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.

Implementing Encryption and Decryption of Data in Python (7)

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)Implementing Encryption and Decryption of Data in Python (8)

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.

Implementing Encryption and Decryption of Data in Python (9)

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.
Implementing Encryption and Decryption of Data in Python (2024)

FAQs

How do you implement encryption and decryption in Python? ›

Steps:
  1. Import rsa library.
  2. Generate public and private keys with rsa. ...
  3. Encode the string to byte string.
  4. Then encrypt the byte string with the public key.
  5. Then the encrypted string can be decrypted with the private key.
  6. The public key can only be used for encryption and the private can only be used for decryption.
Aug 14, 2024

Which algorithm is best for encryption and decryption in Python? ›

Some of the most common and widely used algorithms are AES, RSA, and Fernet. AES is a symmetric algorithm that uses the same key for encryption and decryption, and it is fast and efficient for large data.

How to decrypt AES-256 in Python? ›

How to encrypt and decrypt text using AES in python?
  1. Process. Get the input message text. In AES the same key used for both encryption and decryption. Generate the secret key. Define the mode of AES. ...
  2. Sample Code. #import crypto and base64. from Crypto.Cipher import AES. import base64. message = ...
  3. Screenshots.

Can you briefly explain how encryption and decryption work? ›

How encryption works. Encryption works by encoding “plaintext” into “ciphertext,” typically through the use of cryptographic mathematical models known as algorithms. To decode the data back to plaintext requires the use of a decryption key, a string of numbers or a password also created by an algorithm.

How do you implement data encryption? ›

Implement encryption in your application: Integrate encryption into your application code. You can use encryption libraries such as OpenSSL or Bcrypt to simplify the process. Test your implementation: Verify that the encryption and decryption processes work as expected and that the encrypted data remains secure.

How to encrypt and decrypt data? ›

With public-key/asymmetric encryption, the sender uses a publicly known key to encrypt the data. The receiver has the private key that forms the other half of the public/private key pair. The receiver can decrypt the data by using the private key in combination with the public key.

Which Python library is best for encryption? ›

Best Python Cryptography Libraries for Secure Data Encryption
  • Table of Contents.
  • PyCryptodome. A self-contained cryptographic library, PyCryptodome is a popular choice for developers who want to implement encryption algorithms in Python. ...
  • Cryptography. ...
  • PyNaCl. ...
  • PyOpenSSL. ...
  • Fernet. ...
  • Keyczar. ...
  • M2Crypto.
Apr 22, 2023

What is the strongest encryption algorithm? ›

AES 256-bit encryption is the strongest and most robust encryption standard that is commercially available today. While it is theoretically true that AES 256-bit encryption is harder to crack than AES 128-bit encryption, AES 128-bit encryption has never been cracked.

Which language is best for encryption and decryption? ›

Here are the top 10 best programming languages for cryptography.
  • Java: The Java Cryptography Extension offers a cryptography API for Java (JCE). ...
  • Python: Another well-liked language for cryptography is Python. ...
  • C++: Crypto++, a C++ library of cryptographic algorithms, is one factor in its popularity for cryptography.
Jan 7, 2023

How hard is it to decrypt AES? ›

AES-256 encryption is virtually uncrackable using any brute-force method. It would take millions of years to break it using the current computing technology and capabilities. However, no encryption standard or system is completely secure. In 2009, a cryptanalysis discovered a possible related-key attack.

How long does it take to decrypt AES 256? ›

With the right quantum computer, AES-128 would take about 2.61*10^12 years to crack, while AES-256 would take 2.29*10^32 years. For reference, the universe is currently about 1.38×10^10 years old, so cracking AES-128 with a quantum computer would take about 200 times longer than the universe has existed.

Is 256 AES a weak cipher? ›

AES-256 is a symmetric encryption algorithm, meaning that the same key is used for both encryption and decryption processes. The unparalleled strength of AES-256 lies in its formidable key length and the intricate complexity of its encryption process.

Which algorithm is used for encryption and decryption? ›

Symmetric Encryption. Symmetric encryption algorithms use the same secret key for both encryption and decryption. This means that the sender and the recipient of an encrypted message need to share a copy of the secret key via a secure channel before starting to send encrypted data.

How do you calculate encryption and decryption? ›

Encrypt a message: To encrypt a message, first convert it to a number m. Then compute the ciphertext c = m^e mod n. Decrypt a message: To decrypt a message, compute the plaintext m = c^d mod n.

What is encryption and decryption for dummies? ›

In public keys, two keys are used. The public key will encrypt data, while the private key will decrypt data. It is referred to as a public key because anyone can use the key to encrypt data. No hacker can read, interpret or decipher the original information once encrypted using a public key.

How to encrypt and decrypt a message using RSA algorithm Python? ›

Setting Up Python Environment with “pycryptodome”
  1. Step 1: Installing libraries in Python. ...
  2. Step 2: Generating RSA Key Pair. ...
  3. Step 3: Encrypting Data with Public Key. ...
  4. Step 4 : Decrypting Data with Private Key. ...
  5. Step 5: Result.
Jan 20, 2024

Is Python an ideal programming language for creating encryption and decryption applications? ›

Python is one of the most popular programming languages in the world. It's a general-purpose language, which means it's used for a wide range of tasks, including cryptography. It's also beginner-friendly, so it's an excellent place to start if you're new to coding.

How to encrypt a password using Python? ›

There are various Python modules that are used to hide the user's inputted password, among them one is maskpass() module. In Python with the help of maskpass() module and base64() module we can hide the password of users with asterisk(*) during input time and then with the help of base64() module it can be encrypted.

How to encrypt a file in Python? ›

Encrypt the file using the key generated
  1. Open the file that contains the key.
  2. Initialize the Fernet object and store it in the fernet variable.
  3. Read the original file.
  4. Encrypt the file and store it into an object.
  5. Then write the encrypted data into the same file nba. csv.
Jun 3, 2022

Top Articles
Five Tips on How to Be a Stay at Home Mom Financially
Dragon Age 4: 5 Reasons Why Solas Should Be Redeemed (And 5 Why He Needs To Die)
English Bulldog Puppies For Sale Under 1000 In Florida
Katie Pavlich Bikini Photos
Gamevault Agent
Pieology Nutrition Calculator Mobile
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Compare the Samsung Galaxy S24 - 256GB - Cobalt Violet vs Apple iPhone 16 Pro - 128GB - Desert Titanium | AT&T
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Craigslist Dog Kennels For Sale
Things To Do In Atlanta Tomorrow Night
Non Sequitur
Crossword Nexus Solver
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Geometry Review Quiz 5 Answer Key
Hobby Stores Near Me Now
Icivics The Electoral Process Answer Key
Allybearloves
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Marquette Gas Prices
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Vera Bradley Factory Outlet Sunbury Products
Pixel Combat Unblocked
Movies - EPIC Theatres
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Mia Malkova Bio, Net Worth, Age & More - Magzica
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Where Can I Cash A Huntington National Bank Check
Topos De Bolos Engraçados
Sand Castle Parents Guide
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hello – Cornerstone Chapel
Stoughton Commuter Rail Schedule
Selly Medaline
Latest Posts
Article information

Author: Jerrold Considine

Last Updated:

Views: 6013

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Jerrold Considine

Birthday: 1993-11-03

Address: Suite 447 3463 Marybelle Circles, New Marlin, AL 20765

Phone: +5816749283868

Job: Sales Executive

Hobby: Air sports, Sand art, Electronics, LARPing, Baseball, Book restoration, Puzzles

Introduction: My name is Jerrold Considine, I am a combative, cheerful, encouraging, happy, enthusiastic, funny, kind person who loves writing and wants to share my knowledge and understanding with you.