AES Encryption in Python
Encrypt and decrypt data with AES-256-GCM in Python using the cryptography library — with examples.
Published:
Tags: AES encryption Python, Python AES-256 GCM, cryptography library Python
AES Encryption in Python Python's library (PyCA) provides production-grade AES-256-GCM encryption in a clean API. This guide covers the AESGCM primitive, Fernet for simpler use cases, key management patterns, password-based encryption, and integration with Django and Flask. --- Which library should I choose? | Library | Status | GCM support | Notes | |---------|--------|-------------|-------| | (PyCA) | Active | Yes | Recommended — uses OpenSSL | | | Active | Yes | Drop-in PyCrypto replacement; fine for legacy systems | | | Unmaintained (2013) | Limited | Do not use | | | Active | ChaCha20-Poly1305 | Based on libsodium; excellent alternative | How do I implement AES-256-GCM core? How do I use associated data (AAD)? AAD is authenticated but not encrypted — useful for binding ciphertext to…
Frequently Asked Questions
How do I implement AES encryption in Python?
Use the `cryptography` library (PyCA). Install with `pip install cryptography`. Import `AESGCM` from `cryptography.hazmat.primitives.ciphers.aead`. Generate a 32-byte key with `os.urandom(32)`, a 12-byte nonce with `os.urandom(12)`, then call `AESGCM(key).encrypt(nonce, plaintext, None)`.
What Python library should I use for AES?
Use `cryptography` (PyCA) — it is the officially recommended library, actively maintained, uses OpenSSL under the hood, and supports modern AEAD modes (AES-GCM, ChaCha20-Poly1305). Do not use PyCrypto (unmaintained) or PyCryptodome unless you have a specific compatibility requirement.
How do I use the cryptography package in Python?
Install with `pip install cryptography`. For AES-GCM: `from cryptography.hazmat.primitives.ciphers.aead import AESGCM`. Create an instance: `aesgcm = AESGCM(key)`. Encrypt: `ciphertext = aesgcm.encrypt(nonce, data, aad)`. Decrypt: `plaintext = aesgcm.decrypt(nonce, ciphertext, aad)`. If authentication fails, `InvalidTag` is raised.
How do I handle AES key storage in Python?
Never hardcode keys in source. In production, use a secrets manager: `boto3` for AWS Secrets Manager, `google-cloud-secret-manager` for GCP, or HashiCorp Vault's Python client. For development, use environment variables via `os.environ['MY_KEY']` or a `.env` file excluded from version control.
What is Fernet encryption in Python?
Fernet is a high-level symmetric encryption recipe in the cryptography library that combines AES-128-CBC with HMAC-SHA256 and includes a timestamp. It is simpler than raw AES-GCM but uses 128-bit keys and CBC mode. For new code, prefer AESGCM directly for AES-256-GCM. Fernet is a good choice when you want a simple 'encrypt/decrypt' API without managing nonces.
All articles · theproductguy.in