Skip to content

Instantly share code, notes, and snippets.

@sachadee
Created July 7, 2024 23:54
Show Gist options
  • Save sachadee/3ec4df29e9eb0f0b6541e16e3ba46fee to your computer and use it in GitHub Desktop.
Save sachadee/3ec4df29e9eb0f0b6541e16e3ba46fee to your computer and use it in GitHub Desktop.
Python code to crypt a message with AES-GCM 128 bits
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64
def encrypt_aes_gcm(plaintext, key):
cipher = AES.new(key, AES.MODE_GCM)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)
return ciphertext, cipher.nonce, tag
# Example usage
plaintext = 'I love medium'
key = get_random_bytes(32) # AES key length is 16 bytes (128 bits)
# Encrypt
ciphertext, nonce, tag = encrypt_aes_gcm(plaintext.encode(), key)
print("Ciphertext:", ciphertext)
print("Nonce:", nonce)
print("Tag:", tag)
key_base64 = base64.b64encode(key).decode('utf-8')
ciphertext_base64 = base64.b64encode(ciphertext).decode('utf-8')
nonce_base64 = base64.b64encode(nonce).decode('utf-8')
tag_base64 = base64.b64encode(tag).decode('utf-8')
print(key_base64, ciphertext_base64, nonce_base64, tag_base64)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment