Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Authenticated-Encryption/AE-with-MACs/Encrypt-and-MAC/enc-and-mac.py
1402 views
1
"""
2
An illustration of Encrypt and MAC form of Authenticated Encryption with MACs
3
MAC algorithm: CBC-MAC
4
Encryption: AES in CBC mode
5
Note that this is only for illustrative purposes (the script is vulnerable to CBC-MAC forgery and more implementation attacks)
6
"""
7
8
from Crypto.Cipher import AES
9
from os import urandom
10
from Crypto.Util.number import *
11
12
key = urandom(16)
13
iv = urandom(16)
14
mac_key = urandom(16)
15
16
blocksize = 16
17
18
def pad(input_str, blocksize):
19
input_str += chr(blocksize - len(input_str) % blocksize)*(blocksize - len(input_str) % blocksize)
20
assert len(input_str) % blocksize == 0
21
return input_str
22
23
def unpad(input_str):
24
return input_str[:-ord(input_str[-1])]
25
26
def cbc_mac_gen(input_str, iv, mac_key, blocksize):
27
input_str = pad(input_str, blocksize)
28
obj1 = AES.new(mac_key, AES.MODE_CBC, iv)
29
auth_tag = obj1.encrypt(input_str)[-blocksize:]
30
return auth_tag.encode("hex")
31
32
def cbc_mac_auth(input_str, iv, mac_key, blocksize, auth_tag):
33
input_str = pad(input_str, blocksize)
34
obj1 = AES.new(mac_key, AES.MODE_CBC, iv)
35
chk_tag = obj1.encrypt(input_str)[-blocksize:].encode("hex")
36
if chk_tag == auth_tag:
37
print "Verification Successful"
38
return 1
39
else:
40
print "Verification Failed"
41
return 0
42
43
def encrypt(input_str, iv, key, blocksize):
44
input_str = pad(input_str, blocksize)
45
obj1 = AES.new(key, AES.MODE_CBC, iv)
46
ciphertext = obj1.encrypt(input_str)
47
return ciphertext.encode("hex")
48
49
def decrypt(ciphertext, iv, key, blocksize):
50
ciphertext = ciphertext.decode("hex")
51
obj1 = AES.new(key, AES.MODE_CBC, iv)
52
plaintext = obj1.decrypt(ciphertext)
53
return unpad(plaintext)
54
55
def encrypt_and_mac(input_str, iv, key, mac_key, blocksize):
56
return iv.encode("hex") + ":" + encrypt(input_str, iv, key, blocksize) + ":" + cbc_mac_gen(input_str, iv, mac_key, blocksize)
57
58
def decrypt_and_auth(cookie, key, blocksize, mac_key):
59
iv, ciphertext, auth_tag = cookie.split(":")
60
iv = iv.decode("hex")
61
input_str = decrypt(ciphertext, iv, key, blocksize)
62
if cbc_mac_auth(input_str, iv, mac_key, blocksize, auth_tag):
63
return "Plaintext: ", input_str
64
else:
65
return "Verification failed, so nothing for you!"
66
67
str1 = encrypt_and_mac("testplaintext", iv, key, mac_key, 16)
68
print str1
69
print decrypt_and_auth(str1, key, 16, mac_key)
70