PyCryptodomeX

3.23.0 · active · verified Sat Mar 28

PyCryptodomeX is a self-contained Python package providing low-level cryptographic primitives. It is a fork of the unmaintained PyCrypto library, offering numerous enhancements like authenticated encryption modes, Hybrid Public Key Encryption (HPKE), accelerated AES, and elliptic curve cryptography. It is actively maintained, with version 3.23.0 being the latest, and releases occur frequently. It supports Python 2.7, Python 3.7 and newer, and PyPy.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates symmetric encryption and decryption using AES in CBC mode with PyCryptodomeX. It covers key and IV generation, data padding, encryption, and subsequent decryption and unpadding.

from Cryptodome.Cipher import AES
from Cryptodome.Random import get_random_bytes
from Cryptodome.Util.Padding import pad, unpad

# --- Encryption ---

# Generate a random 16-byte key for AES-128
key = get_random_bytes(16)

# Generate a random 16-byte IV for CBC mode
iv = get_random_bytes(16)

# The data to encrypt must be bytes
data_to_encrypt = b"My secret message that needs to be encrypted."

# Create an AES cipher object in CBC mode
cipher = AES.new(key, AES.MODE_CBC, iv)

# Pad the data to be a multiple of the block size (16 bytes for AES)
padded_data = pad(data_to_encrypt, AES.block_size)

# Encrypt the padded data
ciphertext = cipher.encrypt(padded_data)

print(f"Original data: {data_to_encrypt}")
print(f"Key (hex): {key.hex()}")
print(f"IV (hex): {iv.hex()}")
print(f"Ciphertext (hex): {ciphertext.hex()}")

# --- Decryption ---

# In a real scenario, key, iv, and ciphertext would be transmitted
# to the receiver. For this example, we reuse them.

# Create a new AES cipher object for decryption (same key and IV)
decipher = AES.new(key, AES.MODE_CBC, iv)

# Decrypt the ciphertext
decrypted_padded_data = decipher.decrypt(ciphertext)

# Unpad the decrypted data to get the original plaintext
decrypted_data = unpad(decrypted_padded_data, AES.block_size)

print(f"Decrypted data: {decrypted_data}")

assert decrypted_data == data_to_encrypt
print("Encryption and decryption successful!")

view raw JSON →