Skip to content

Instantly share code, notes, and snippets.

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 LeeHampton/197b8a5ab485efbfd0c6ee83cd6dcdde to your computer and use it in GitHub Desktop.
Save LeeHampton/197b8a5ab485efbfd0c6ee83cd6dcdde to your computer and use it in GitHub Desktop.
aes_gcm encryption
from Crypto.Cipher import AES
import binascii, os
def encrypt_AES_GCM(msg, secretKey):
aesCipher = AES.new(secretKey, AES.MODE_GCM)
ciphertext, authTag = aesCipher.encrypt_and_digest(msg)
print("ciphertext: {}, authTag: {}".format(ciphertext, authTag))
return (ciphertext, aesCipher.nonce, authTag)
def decrypt_AES_GCM(encryptedMsg, secretKey):
(ciphertext, nonce, authTag) = encryptedMsg
aesCipher = AES.new(secretKey, AES.MODE_GCM, nonce)
plaintext = aesCipher.decrypt_and_verify(ciphertext, authTag)
return plaintext
# secretKey = os.urandom(16) # 128-bit random encryption key
# print("Encryption key:", binascii.hexlify(secretKey))
secretKey = binascii.hexlify('fooofooofoopfooo'.encode('utf-8'))
print("Encryption key:", secretKey)
msg = b'ultra secret message'
encryptedMsg = encrypt_AES_GCM(msg, secretKey)
print("encryptedMsg", {
'ciphertext': inascii.hexlify(encryptedMsg[0]),
'aesIV': binascii.hexlify(encryptedMsg[1]),
'authTag': binascii.hexlify(encryptedMsg[2])
})
decryptedMsg = decrypt_AES_GCM(encryptedMsg, secretKey)
print("decryptedMsg", decryptedMsg)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment