Path: blob/master/Authenticated-Encryption/AE-with-MACs/Encrypt-and-MAC/enc-and-mac.py
1402 views
"""1An illustration of Encrypt and MAC form of Authenticated Encryption with MACs2MAC algorithm: CBC-MAC3Encryption: AES in CBC mode4Note that this is only for illustrative purposes (the script is vulnerable to CBC-MAC forgery and more implementation attacks)5"""67from Crypto.Cipher import AES8from os import urandom9from Crypto.Util.number import *1011key = urandom(16)12iv = urandom(16)13mac_key = urandom(16)1415blocksize = 161617def pad(input_str, blocksize):18input_str += chr(blocksize - len(input_str) % blocksize)*(blocksize - len(input_str) % blocksize)19assert len(input_str) % blocksize == 020return input_str2122def unpad(input_str):23return input_str[:-ord(input_str[-1])]2425def cbc_mac_gen(input_str, iv, mac_key, blocksize):26input_str = pad(input_str, blocksize)27obj1 = AES.new(mac_key, AES.MODE_CBC, iv)28auth_tag = obj1.encrypt(input_str)[-blocksize:]29return auth_tag.encode("hex")3031def cbc_mac_auth(input_str, iv, mac_key, blocksize, auth_tag):32input_str = pad(input_str, blocksize)33obj1 = AES.new(mac_key, AES.MODE_CBC, iv)34chk_tag = obj1.encrypt(input_str)[-blocksize:].encode("hex")35if chk_tag == auth_tag:36print "Verification Successful"37return 138else:39print "Verification Failed"40return 04142def encrypt(input_str, iv, key, blocksize):43input_str = pad(input_str, blocksize)44obj1 = AES.new(key, AES.MODE_CBC, iv)45ciphertext = obj1.encrypt(input_str)46return ciphertext.encode("hex")4748def decrypt(ciphertext, iv, key, blocksize):49ciphertext = ciphertext.decode("hex")50obj1 = AES.new(key, AES.MODE_CBC, iv)51plaintext = obj1.decrypt(ciphertext)52return unpad(plaintext)5354def encrypt_and_mac(input_str, iv, key, mac_key, blocksize):55return iv.encode("hex") + ":" + encrypt(input_str, iv, key, blocksize) + ":" + cbc_mac_gen(input_str, iv, mac_key, blocksize)5657def decrypt_and_auth(cookie, key, blocksize, mac_key):58iv, ciphertext, auth_tag = cookie.split(":")59iv = iv.decode("hex")60input_str = decrypt(ciphertext, iv, key, blocksize)61if cbc_mac_auth(input_str, iv, mac_key, blocksize, auth_tag):62return "Plaintext: ", input_str63else:64return "Verification failed, so nothing for you!"6566str1 = encrypt_and_mac("testplaintext", iv, key, mac_key, 16)67print str168print decrypt_and_auth(str1, key, 16, mac_key)6970