Created
May 31, 2020 13:32
-
-
Save LeeHampton/197b8a5ab485efbfd0c6ee83cd6dcdde to your computer and use it in GitHub Desktop.
aes_gcm encryption
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 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