PyCryptodome

3.23.0 · active · verified Sat Mar 28

PyCryptodome is a self-contained Python package providing low-level cryptographic primitives. It offers a comprehensive suite of algorithms for encryption, decryption, hashing, and digital signatures, acting as a maintained fork and drop-in replacement for the outdated PyCrypto library. It supports Python 2.7, Python 3.7+, and PyPy, with a consistent release cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates symmetric encryption and decryption using AES in GCM (Galois/Counter Mode), an authenticated encryption mode. It shows how to derive a key from a password using PBKDF2, generate a random salt and nonce, encrypt data, and then decrypt and verify its integrity.

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Protocol.KDF import PBKDF2
import os

# Simulate a password for key derivation
password = os.environ.get('CRYPTO_PASSWORD', 'mysecretpassword').encode('utf-8')

# Generate a random salt
salt = get_random_bytes(16)

# Derive a strong key from the password and salt
# Use default iterations (or a high number like 1000000)
key = PBKDF2(password, salt, dkLen=32) # 32 bytes for AES-256

# The data to encrypt
data = b"This is a super secret message."

# Encrypt with AES GCM
# A nonce is automatically generated by AES.new() in GCM mode
cipher = AES.new(key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(data)
nonce = cipher.nonce

print(f"Original: {data}")
print(f"Salt: {salt.hex()}")
print(f"Nonce: {nonce.hex()}")
print(f"Ciphertext: {ciphertext.hex()}")
print(f"Tag: {tag.hex()}")

# --- Decryption ---
# Re-derive the key using the same password and salt
decryption_key = PBKDF2(password, salt, dkLen=32)

# Create a new cipher object for decryption using the received key and nonce
decrypt_cipher = AES.new(decryption_key, AES.MODE_GCM, nonce=nonce)

# Decrypt and verify
try:
    plaintext = decrypt_cipher.decrypt_and_verify(ciphertext, tag)
    print(f"Decrypted: {plaintext}")
except ValueError:
    print("Decryption failed or message was tampered with!")

view raw JSON →