Hazmat with AES GCM with Key DerivationAES GCM converts the AES method into a stream cipher. It thus does not need padding and is faster than other modes. GCM can also support AEAD (Authenticated Encryption with Additional Data), and where we can add additional data into the cipher, and which can be used to authenticate the cipher. This addditional data might bind the cipher to a given network port or session. This means that an intruder cannot replay a cipher because they cannot create the same additional data. In this case we will use HDKF to generate a 256-bit encryption key. |
Code
Hazmat supports core cryptographical primitives for AES GCM and for AEAD:
import os from cryptography.hazmat.primitives.ciphers.aead import AESGCM import sys import binascii from cryptography.hazmat.primitives.kdf.hkdf import HKDF from cryptography.hazmat.primitives import hashes msg = "a message" add = "additional data" password="qwerty" length=32 # 256 bits if (len(sys.argv)>1): password=str(sys.argv[1]) if (len(sys.argv)>2): msg=str(sys.argv[2]) if (len(sys.argv)>3): add=str(sys.argv[3]) hkdf = HKDF(algorithm=hashes.SHA256(), length=length,salt=b"", info=b"") mykey=hkdf.derive(password.encode()) print ("Password: ",password) print ("Data:\t",msg) print ("Additional data:\t",add) # key = ChaCha20Poly1305.generate_key() aesgcm = AESGCM(mykey) nonce = os.urandom(12) cipher = aesgcm.encrypt(nonce, msg.encode(), add.encode()) rtn=aesgcm.decrypt(nonce, cipher, add.encode()) print ("\nKey:\t",binascii.b2a_hex(mykey).decode()) print ("Nonce:\t",binascii.b2a_hex(nonce).decode()) print ("\nCipher:\t",binascii.b2a_hex(cipher).decode()) print ("Decrypted:\t",rtn.decode())
A sample run is:
Password: qwerty Data: a message Additional data: additional data Key: 697b0111081294978a075c6cae24729665be7f5a646007ac90aadc3954a484f8 Nonce: a3bf6cf2b981c84a2f07c99c Cipher: 74a798cbd1025f1a20006109f47e13f0769684ca5be1a0736b Decrypted: a message