Skip to content

Instantly share code, notes, and snippets.

@brianonn
Created May 26, 2022 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brianonn/8378844df81ec2cdf461ca3027f26c8e to your computer and use it in GitHub Desktop.
Save brianonn/8378844df81ec2cdf461ca3027f26c8e to your computer and use it in GitHub Desktop.
AESGCM in python
# from https://stackoverflow.com/a/59835994
# also see: https://soatok.blog/2020/05/13/why-aes-gcm-sucks/
import secrets
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# Generate a random secret key (AES256 needs 32 bytes)
key = secrets.token_bytes(32)
# Encrypt a message
nonce = secrets.token_bytes(12) # GCM mode needs 12 fresh bytes every time (don't skip this !)
ciphertext = nonce + AESGCM(key).encrypt(nonce, b"Message", b"")
# Decrypt (raises InvalidTag if using wrong key or corrupted ciphertext)
msg = AESGCM(key).decrypt(ciphertext[:12], ciphertext[12:], b"")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment