Created
May 26, 2022 01:11
-
-
Save brianonn/8378844df81ec2cdf461ca3027f26c8e to your computer and use it in GitHub Desktop.
AESGCM in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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