Hazmat with AES GCM
[Hazmat Home][Home]
AES 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 generate a random 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 ChaCha20Poly1305 import sys import binascii msg = "a message" add = "additional data" if (len(sys.argv)>1): msg=str(sys.argv[1]) if (len(sys.argv)>2): add=str(sys.argv[2]) print ("Data:\t",msg) print ("Additional data:\t",add) key = ChaCha20Poly1305.generate_key() chacha = ChaCha20Poly1305(key) nonce = os.urandom(12) cipher = chacha.encrypt(nonce, msg.encode(), add.encode()) rtn=chacha.decrypt(nonce, cipher, add.encode()) print ("\nKey:\t",binascii.b2a_hex(key).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:
Data: a message Additional data: additional data Key: cc959f846f440701bfdfa791b6a048901b0a20adcb0b61ec8f08ce6ae130c46f Nonce: b529ed416f1ff9089b5f8c67 Cipher: d77ef575d5e163d11b4ecc30cd9be8b6d6c89ba9c0def0d981 Decrypted: a message