To perform encryption and decryption using AES-256 with the PyCrypto library in Python, follow these steps:
1. Install the required library
Install pycryptodome, the maintained fork of pycrypto:
bash Copy code
pip install pycryptodome
2. Code example for AES-256 encryption and decryption
Here’s a complete implementation:
Python Copy code
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
import base64
# Function to encrypt the plaintext
def encrypt(plaintext, key):
cipher = AES.new(key, AES.MODE_CBC) # Create AES cipher in CBC mode
iv = cipher.iv # Initialization vector
ciphertext = cipher.encrypt(pad(plaintext.encode(‘utf-8’), AES.block_size))
return base64.b64encode(iv).decode(‘utf-8’), base64.b64encode(ciphertext).decode(‘utf-8’)
# Function to decrypt the ciphertext
def decrypt(iv, ciphertext, key):
iv = base64.b64decode(iv)
ciphertext = base64.b64decode(ciphertext)
cipher = AES.new(key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext.decode(‘utf-8’)
# Example usage
if __name__ == “__main__”:
# Generate a random 32-byte (256-bit) key for AES-256
key = get_random_bytes(32)
# Example plaintext
plaintext = “This is an AES-256 encrypted message.”
# Encrypt the plaintext
iv, encrypted_message = encrypt(plaintext, key)
print(f”IV (Base64): {iv}”)
print(f”Encrypted Message (Base64): {encrypted_message}”)
# Decrypt the ciphertext
decrypted_message = decrypt(iv, encrypted_message, key)
print(f”Decrypted Message: {decrypted_message}”)
Explanation
Key: AES-256 requires a 256-bit (32-byte) key, which is generated randomly in the example using get_random_bytes(32).
Padding: Since AES operates on fixed block sizes, the plaintext is padded using Crypto.Util.Padding.pad.
Initialization Vector (IV): A new IV is generated for each encryption operation for security.
Base64 Encoding: The IV and ciphertext are encoded in Base64 to make them suitable for storage or transmission as strings.
Output
The code will print the Base64-encoded IV and ciphertext, followed by the decrypted message. Ensure the same key is used for both encryption and decryption.