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'
Create a free account and build your private vault. Share publicly whenever you want.