Hazmat CMAC
[Hazmat Home][Home]
CMACs (Cipher-based message authentication codes) create a message authentication codes (MACs) using a block cipher and a secret key. They differ from HMACs in that they use a symmetric key method for the MACs rather than a hashing method.
|
Code
import os import sys import binascii from cryptography.hazmat.primitives import cmac from cryptography.hazmat.primitives.ciphers import algorithms message = "message" ctype="TripleDES" if (len(sys.argv)>1): message=str(sys.argv[1]) if (len(sys.argv)>2): ctype=str(sys.argv[2]) message=message.encode() key = os.urandom(32) c = cmac.CMAC(algorithms.AES(key)) if (ctype=="AES"): c = cmac.CMAC(algorithms.AES(key)) elif (ctype=="Camellia"): c = cmac.CMAC(algorithms.Camellia(key)) elif (ctype=="TripleDES"): key = os.urandom(16) c = cmac.CMAC(algorithms.TripleDES(key)) elif (ctype=="Blowfish"): c = cmac.CMAC(algorithms.Blowfish(key)) elif (ctype=="CAST5"): key = os.urandom(16) c = cmac.CMAC(algorithms.CAST5(key)) elif (ctype=="SEED"): key = os.urandom(16) c = cmac.CMAC(algorithms.SEED(key)) c.update(message) c_copy = c.copy() signature = c.finalize() print (f"Message: {message.decode()}" ) print (f"Type: {ctype}" ) print (f"Key: {binascii.b2a_hex(key).decode()}") print (f"CMAC signature: {binascii.b2a_hex(signature).decode()}") try: rtn=c_copy.verify(signature) print ("Signature matches") except: print ("Signature does not match")
A sample run is:
Message: message Type: AES Key: 5b2997c9aca4bd4ac5081e6551d1faabcae25d2ed9ac8b58b2acc643d963f425 CMAC signature: 6c8de15306d8ed7d8e0badf945d38561 Signature matches