AES GCM (Python)AES GCM (Galois Counter Mode) is a stream cipher mode for AES. It is based on the CTR mode, but is converted into a stream cipher. This provides low latency in the encryption/decryption process, and which is fast to process. As it is a stream cipher, it does not require padding. Along with this it integrates AEAD (Authenticated Encryption with Associated Data) for the authentication of the message. With AES-GCM, we have an encryption key (normally 128 bits or 256 bits) and a message, and then generate the cipher, a random nonce, and an authentication tag (and which is a message authentication code (MAC)). The tag helps authenticate the message [With PBKDF2 SHA-256 password]. |
Code
In the following, we will take a password and then generate a 256-bit key by taking a SHA-256 hash of the password. An outline of the code is:
from Crypto.Cipher import AES import hashlib import sys import binascii plaintext='hello how are you?' password='qwerty123' if (len(sys.argv)>1): plaintext=(sys.argv[1]) if (len(sys.argv)>2): password=(sys.argv[2]) def encrypt(plaintext,key, mode): encobj = AES.new(key, AES.MODE_GCM) ciphertext,authTag=encobj.encrypt_and_digest(plaintext) return(ciphertext,authTag,encobj.nonce) def decrypt(ciphertext,key, mode): (ciphertext, authTag, nonce) = ciphertext encobj = AES.new(key, mode, nonce) return(encobj.decrypt_and_verify(ciphertext, authTag)) key = hashlib.sha256(password.encode()).digest() print("GCM Mode: Stream cipher and authenticated") print("\nMessage:\t",plaintext) print("Key:\t\t",password) ciphertext = encrypt(plaintext.encode(),key,AES.MODE_GCM) print("Cipher:\t\t",binascii.hexlify(ciphertext[0])) print("Auth Msg:\t",binascii.hexlify(ciphertext[1])) print("Nonce:\t\t",binascii.hexlify(ciphertext[2])) res= decrypt(ciphertext,key,AES.MODE_GCM) print ("\n\nDecrypted:\t",res.decode())
A sample run gives:
GCM Mode: Stream cipher and authenticated Message: hello how are you? Key: qwerty123 Cipher: b'610cb0ee31a04573ced55f942414b1696ffc' Auth Msg: b'c6c1370c50e124949d4fba7a9ae7be5f' Nonce: b'156131666b6ae28acc3c159c6ce982bc' Decrypted: hello how are you?