How to Encrypt and Decrypt Text Using AES in Python?
Share
Condition for Encrypting and Decrypting Text Using AES in Python
Description:
AES (Advanced Encryption Standard) is a symmetric encryption algorithm widely used for secure data encryption.It works with fixed block sizes and keys (128, 192, or 256 bits). In Python, the PyCryptodome library can be used to perform AES encryption and decryption.
Step-by-Step Process
Install PyCryptodome:
Install the library using pip install pycryptodome.
Generate a Key:
Use a random or predefined key of appropriate size (16, 24, or 32 bytes).
Encrypt the Plaintext:
Use AES in a secure mode (e.g., CBC) with an initialization vector (IV) to encrypt the plaintext.
Decrypt the Ciphertext:
Use the same key and IV to reverse the process and retrieve the plaintext.
Sample Code
#Program for encrypt and decrypt text
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64
def pad(text):
return text + (16 - len(text) % 16) * chr(16 - len(text) % 16)
def unpad(text):
return text[:-ord(text[-1])]
#Generate a random key and IV
key = get_random_bytes(16)
iv = get_random_bytes(16)
#Create the AES cipher object for encryption
cipher = AES.new(key, AES.MODE_CBC, iv)
#Encrypt plaintext
plaintext = "Hi! this is ABC from Alphabets."
padded_plaintext = pad(plaintext)
ciphertext = cipher.encrypt(padded_plaintext.encode())
print("Original message:", plaintext)
print("Encrypted message:", base64.b64encode(ciphertext).decode())
#Decrypt ciphertext
decrypt_cipher = AES.new(key, AES.MODE_CBC, iv)
decrypted = decrypt_cipher.decrypt(ciphertext)
decrypted_plaintext = unpad(decrypted.decode())
print("Decrypted message:", decrypted_plaintext)