Python Examples
Convert IP to Integer and Integer To IP in Python
How to Get IPv4/IPv6 Address Range from CIDR in Python?
Compare Two Objects For Equality in Python
How to find Duplicate Elements from a List in Python
Convert Timestamp to datetime in Python
Convert datetime to Timestamp in Python
Generate Random String of Specific Length in Python
Encryption and Decryption of Strings in Python
The string module in Python
Convert string to bytes in Python
Convert bytes to string in Python
Convert string to datetime and datetime to string in Python
Call a function Asynchronously from within a Loop and wait for the Results in Python
Remove Duplicate Elements from a List in Python
Caching in Python with Examples
How to Bulk Insert and Retrieve Data from Redis in Python
How to Write Unit Test in Python
Read and Write CSV Files in Python
Read and Write Data to a Text File in Python
How to Convert CSV to JSON in Python
Create ICS Calendar File in Python
Install Python on Windows 10/11
Install Python on Ubuntu 20.04 or 22.04.3
Python - Install Virtual Environment
How to Find a Specific Field Value from a JSON list in Python
Download and Unzip a Zipped File in Python
Python Install PIP
Python Install Virtual Environment
How to Fix Python Error: string argument without an encoding
Compare Two JSON files in Python
How to Hash a Dictionary Object in Python?
Create a Digital Clock in Python
Create Multiple URLs Using Each Path of a URL in Python
Send an Email with Multiple Attachments using Amazon SES in Python
SQLAlchemy Query Examples for Effective Database Management
SQLAlchemy Query to Find IP Addresses from an IP Range in Bulk
How to Create and Use Configuration files in a Python Project
Check if a Value Already Exists in a List of Dictionary Objects in Python
How to Split Large Files by size in Python?
Fixing - Running Scripts is Disabled on this System Error on Windows
Generating QR Codes in Python
Reading QR Codes in Python
Encryption and Decryption of Strings in Python
- Last updated Apr 25, 2024
Encryption is the process of converting plain text into ciphertext. Ciphertext is not readable until it is converted to plain text. A secret key is required for encryption.
Decryption is the process of converting ciphertext into plain text. A secrte key is required for decryption.
Types of Encryption
There are two types of encryption:
- Symmetric Encryption: Symmetric encryption uses a single key to encrypt and decrypt a text. When communicating using the symmetric encryption, the key needs to be shared so that the person who is receiving the text is able to decrypt it for reading. Symmetric encryption is old technique for encrypting and decrypting a text. Some of the symmetric key encryption algorithm are AES (Advanced Encryption Standard), DES (Data Encryption Standard), etc.
- Asymmetric Encryption: Asymmetric encryption uses two keys - public key and secret key. A public key is made available to anyone who might want to encrypt a text. Anyone with a secret key can decrypt the encrypted text. The secret key is kept secret or exchanged over the internet. A text that is encrypted using the public key can also be decrypted using a secret key. Asymmetric encryption is relatively new technique to encrypt and decrypt a text. Some of the asymmetric key encryption algorithm are DSA, RSA, PKCS, ELGamal, ECC, Diffie-Hellman, etc.
Asymmetric encryption is considered to be more secure than symmetric encryption because asymmetric encrytion uses two keys for encryption and decryption.
Symmetric Encryption/Decryption Example
Follow the steps below to perform symmetric encryption/decryption in Python:
- Install the Python cryptography library using the following command:
- The following code shows how to encrypt and decrypt a string using the Symmetric Encryption technique:
pip install cryptography
from cryptography.fernet import Fernet
# Put this somewhere safe!
key = Fernet.generate_key()
def encrypt_text(plain_text):
f = Fernet(key)
encrypted_text = f.encrypt(bytes(plain_text, "UTF-8"))
return encrypted_text.decode()
def decrypt_text(encrypted_text):
f = Fernet(key)
return f.decrypt(bytes(encrypted_text,"UTF-8")).decode()
#Testing
plain_text = "Hello, this is an important message"
encrypted_text = encrypt_text(plain_text)
print("Encrypted message = %s" %(encrypted_text))
decrypted_text = decrypt_text(encrypted_text)
print("Decrypted message = %s" %(decrypted_text))
The output of the above code is as follows:
Encrypted message = gAAAAABgrTGWd0HZmfNyhK461WZsqnf-MzmALreUzHeBUkpWULx_JUEOR8XoMrLfhTDS0CfO3QnOHE3A0-cY17sH2rCkBiCs9XrNjbzl0pcwfDGG5jiwEpKPVMZS9VfNN8f0AA5jx4sC Decrypted message = Hello, this is an important message
Asymmetric Encryption/Decryption Example
Follow the steps below to perform asymmetric encryption/decryption in Python:
- Install the Python rsa library using the following command:
- The following code shows how to encrypt and decrypt a string using the Asymmetric Encryption technique:
pip install rsa
import rsa
public_key, private_key = rsa.newkeys(512)
def encrypt_text(plain_text):
plain_text = plain_text.encode('utf8')
encrypted_text = rsa.encrypt(plain_text, public_key)
return encrypted_text
def decrypt_text(encrypted_text):
decrypted_text = rsa.decrypt(encrypted_text, private_key)
return decrypted_text.decode("utf-8")
# testing
plain_text = "Hello this is an important message"
encrypted_text = encrypt_text(plain_text)
print("Encrypted text is = %s" %(encrypted_text))
decrypted_text = decrypt_text(encrypted_text)
print("Decrypted text is = %s" %(decrypted_text))
The output of the above code is as follows:
Encrypted text is = b'\x97\xd2\xdb\xccT\xd6K\x0c\xda\xe0\x8d5X\xe6b\x01\xd5\x88\x98\xcb\x8c4TV\x05a\xeb\xac\x0c\x901q\x85\xa8t\x90\xb1\x9e\xbb\x04\xa9c\xbf\xc8\xe5\xcb,\x85\x1e\x84\r\xf8\xe8\x14\x81\xa5\xe1J\xe5+\xe77\x02\xc9' Decrypted text is = Hello this is an important message