Python

AES-GCM Encrypt / Decrypt (cryptography)

admin by @admin ADMIN
Jun 12, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Authenticated symmetric encryption using AES-256-GCM from the `cryptography` package. Stores nonce + ciphertext + tag together as base64 so storage is a single column.
Python
Raw
import base64
import os
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

def encrypt(plaintext: bytes, key: bytes) -> str:
    """key must be 16, 24, or 32 bytes."""
    nonce = os.urandom(12)
    ct = AESGCM(key).encrypt(nonce, plaintext, associated_data=None)
    return base64.b64encode(nonce + ct).decode()

def decrypt(token: str, key: bytes) -> bytes:
    raw = base64.b64decode(token)
    nonce, ct = raw[:12], raw[12:]
    return AESGCM(key).decrypt(nonce, ct, associated_data=None)

key = AESGCM.generate_key(bit_length=256)
cipher = encrypt(b"the secret message", key)
print(cipher)
print(decrypt(cipher, key))   # b'the secret message'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.