IC Improve Code Recipes

Recipe 7.2 · Python

Encrypting Data with AES-GCM

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Some data must be readable by the application but not by someone holding a copy of the database: bank account numbers, national IDs, API credentials for a customer's integration. The legacy helpers use AES in CBC or ECB mode with a fixed IV and no integrity check, so identical values produce identical ciphertext, and an attacker can flip bits without detection.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Install: pip install cryptography

Python AES encryption with a hard-coded key and fixed IV (p144_r7_2_aes_cbc_fixed_iv_before.py)
"""AES encryption with a hard-coded key and fixed IV

Source: ImproveCode, Chapter 7, Recipe 7.2 "Encrypting Data with AES-GCM"
Section: The way it's often written
Book page: 144  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
The cryptography package's AES-CBC with PKCS7 padding mirrors RijndaelManaged defaults.
"""

import base64

from cryptography.hazmat.primitives import padding
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

# Not this: hard-coded key, fixed IV, no tamper detection.
KEY: bytes = "MySecretKey12345".encode("ascii")
IV: bytes = bytes(16)


def encrypt(text: str) -> str:
    padder = padding.PKCS7(128).padder()
    data = padder.update(text.encode("utf-8")) + padder.finalize()
    enc = Cipher(algorithms.AES(KEY), modes.CBC(IV)).encryptor()
    output = enc.update(data) + enc.finalize()
    return base64.b64encode(output).decode("ascii")

The improved recipe

Use AesGcm, an authenticated cipher, with a 256-bit key from a secret store, a fresh random nonce for every message, and a versioned output format that carries the nonce and tag.

Usage, binding each value to the row it belongs to:

Requirements: Python 3.12+. Install: pip install cryptography

Python AES-256-GCM encryptor with versioned payload and associated data (p144_r7_2_aes_gcm_encryptor.py)
"""AES-256-GCM encryptor with versioned payload and associated data

Source: ImproveCode, Chapter 7, Recipe 7.2 "Encrypting Data with AES-GCM"
Section: The improved recipe
Book page: 144-146  -- original C# listing
Converted from C# to Python.
cryptography's AESGCM replaces System.Security.Cryptography.AesGcm. AESGCM
appends the tag to the ciphertext, so it is moved to keep the C# layout.
"""

import base64
import secrets

from cryptography.exceptions import InvalidTag
from cryptography.hazmat.primitives.ciphers.aead import AESGCM


class CryptographicError(Exception):
    pass


class AesGcmEncryptor:
    """AES-256-GCM. Output: version (1) | nonce (12) | tag (16) | ciphertext."""

    _VERSION = 1
    _KEY_SIZE = 32
    _NONCE_SIZE = 12
    _TAG_SIZE = 16
    _HEADER_SIZE = 1 + _NONCE_SIZE + _TAG_SIZE

    def __init__(self, key: bytes) -> None:
        if key is None:
            raise TypeError("key")
        if len(key) != self._KEY_SIZE:
            raise ValueError("The key must be 32 bytes (256 bits).")
        self._key = bytes(key)

    @classmethod
    def generate_key(cls) -> bytes:
        return secrets.token_bytes(cls._KEY_SIZE)

    def encrypt(self, plaintext: bytes, associated_data: bytes = b"") -> bytes:
        nonce = secrets.token_bytes(self._NONCE_SIZE)
        sealed = AESGCM(self._key).encrypt(
            nonce, plaintext, associated_data or None)
        ciphertext, tag = sealed[:-self._TAG_SIZE], sealed[-self._TAG_SIZE:]
        return bytes([self._VERSION]) + nonce + tag + ciphertext

    def decrypt(self, payload: bytes, associated_data: bytes = b"") -> bytes:
        if len(payload) < self._HEADER_SIZE or payload[0] != self._VERSION:
            raise CryptographicError(
                "The payload is truncated or has an unknown version.")

        nonce = payload[1:1 + self._NONCE_SIZE]
        tag = payload[1 + self._NONCE_SIZE:self._HEADER_SIZE]
        ciphertext = payload[self._HEADER_SIZE:]

        # Raises InvalidTag if tampered.
        try:
            return AESGCM(self._key).decrypt(
                nonce, ciphertext + tag, associated_data or None)
        except InvalidTag as ex:
            raise CryptographicError("Authentication tag mismatch.") from ex

    def encrypt_string(self, plaintext: str, context: str) -> str:
        if plaintext is None:
            raise TypeError("plaintext")
        result = self.encrypt(plaintext.encode("utf-8"), context.encode("utf-8"))
        return base64.b64encode(result).decode("ascii")

    def decrypt_string(self, payload: str, context: str) -> str:
        if payload is None:
            raise TypeError("payload")
        plaintext = self.decrypt(
            base64.b64decode(payload), context.encode("utf-8"))
        return plaintext.decode("utf-8")

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Loading the key from configuration and encrypting a bank account number (p146_r7_2_encrypt_bank_account_usage.py)
"""Loading the key from configuration and encrypting a bank account number

Source: ImproveCode, Chapter 7, Recipe 7.2 "Encrypting Data with AES-GCM"
Section: The improved recipe
Book page: 146  -- original C# listing
Converted from C# to Python.
builder.Configuration["Encryption:Key"] becomes the ENCRYPTION__KEY environment
variable (pydantic-settings style naming); usage fragment wrapped in a function.
"""

import base64
import os

from p144_r7_2_aes_gcm_encryptor import AesGcmEncryptor


def store_account_number(account_number: str, customer_id: int) -> str:
    raw = os.environ.get("ENCRYPTION__KEY")
    if raw is None:
        raise RuntimeError("Missing key.")
    key = base64.b64decode(raw)
    encryptor = AesGcmEncryptor(key)

    stored = encryptor.encrypt_string(
        account_number, context=f"Customer:{customer_id}:BankAccount")
    return stored

How it works

GCM is authenticated encryption. Besides the ciphertext it produces a 16-byte tag computed over the ciphertext and the associated data. Decrypt recomputes the tag and throws AuthenticationTagMismatchException (a CryptographicException) if a single bit of the payload, the key or the associated data differs. CBC without a separate MAC gives you no such check.

The nonce must never repeat for the same key, because a repeated nonce in GCM leaks the XOR of the two plaintexts and lets an attacker forge tags. Twelve random bytes from RandomNumberGenerator per message make a collision vanishingly unlikely for any realistic volume. The nonce isn't secret, so it travels at the front of the payload, followed by the tag.

The version byte costs nothing and saves a painful migration later. If you ever change algorithm or layout, new payloads get version 2, and Decrypt can still read version 1.

The context string is associated data: authenticated but not encrypted or stored. Binding the ciphertext to Customer:42:BankAccount means an attacker with write access to the table can't copy customer 42's encrypted account number into their own row; decryption fails because the context doesn't match.

A new AesGcm object per call keeps the class thread-safe without locks. Creating one is cheap compared to the database round trip around it.

Variations and pitfalls

  • The key is the whole secret. Keep it in Key Vault or another secret store (Chapter 6), never in source or in the same database as the data. Generate it with GenerateKey() and store it as Base64.
  • Plan key rotation: add a key ID to the header (a second byte, for example), keep old keys for decryption, and re-encrypt rows in the background.
  • NIST guidance limits random 96-bit nonces to about 2^32 messages per key. If you encrypt billions of values, rotate keys long before that.
  • AesGcm.IsSupported is false on a few platforms (some older Linux builds without a suitable OpenSSL, for example). Check it at startup if you deploy beyond Windows.
  • For data that only your own app needs to round-trip, such as cookies or short-lived tokens, the ASP.NET Core Data Protection API (IDataProtector) handles keys and rotation for you. Use AES-GCM directly when the data lives for years or is shared with other systems.
  • SQL Server's Always Encrypted is the other option for column encryption, with keys that never reach the database server. It's more setup but needs no application crypto code.

On .NET Framework

AesGcm does not exist on .NET Framework. On 4.8, use AesCng in CBC mode with a random IV and an HMAC-SHA-256 over IV and ciphertext (encrypt-then-MAC), verified with a constant-time compare before decrypting, or use a vetted library. Keep the same versioned layout so data can move to AES-GCM when the app moves to modern .NET.