Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Authenticated-Encryption/AE-with-MACs/MAC-then-Encrypt/mac-then-encrypt.py
1402 views
1
"""
2
An illustration of MAC then Encrypt technique 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
even the unpad function is vulnerable!)
7
"""
8
9
from Crypto.Cipher import AES
10
from os import urandom
11
from Crypto.Util.number import *
12
13
key = urandom(16)
14
iv = urandom(16)
15
mac_key = urandom(16)
16
17
blocksize = 16
18
19
def pad(input_str, blocksize):
20
input_str += chr(blocksize - len(input_str) % blocksize)*(blocksize - len(input_str) % blocksize)
21
assert len(input_str) % blocksize == 0
22
return input_str
23
24
def unpad(input_str):
25
return input_str[:-ord(input_str[-1])]
26
27
def cbc_mac_gen(input_str, iv, mac_key, blocksize):
28
input_str = pad(input_str, blocksize)
29
obj1 = AES.new(mac_key, AES.MODE_CBC, iv)
30
auth_tag = obj1.encrypt(input_str)[-blocksize:]
31
return auth_tag.encode("hex")
32
33
def cbc_mac_auth(input_str, iv, mac_key, blocksize, auth_tag):
34
input_str = pad(input_str, blocksize)
35
obj1 = AES.new(mac_key, AES.MODE_CBC, iv)
36
chk_tag = obj1.encrypt(input_str)[-blocksize:]
37
if chk_tag == auth_tag:
38
print "Verification Successful"
39
return 1
40
else:
41
print "Verification Failed"
42
return 0
43
44
def encrypt(input_str, iv, key, blocksize):
45
input_str = pad(input_str, blocksize)
46
obj1 = AES.new(key, AES.MODE_CBC, iv)
47
ciphertext = obj1.encrypt(input_str)
48
return ciphertext.encode("hex")
49
50
def decrypt(ciphertext, iv, key, blocksize):
51
obj1 = AES.new(key, AES.MODE_CBC, iv)
52
plaintext = obj1.decrypt(ciphertext)
53
return unpad(plaintext)
54
55
def mac_then_encrypt(input_str, iv, key, mac_key, blocksize):
56
tag = cbc_mac_gen(input_str, iv, mac_key, blocksize)
57
tag = tag.decode("hex")
58
plaintext = input_str + ":" + tag
59
ciphertext = encrypt(plaintext, iv, key, blocksize)
60
return iv.encode("hex") + ":" + ciphertext
61
62
def auth_check(cookie, iv, key, mac_key, blocksize):
63
iv, ciphertext = cookie.split(":")
64
iv = iv.decode("hex")
65
ciphertext = ciphertext.decode("hex")
66
plaintext = decrypt(ciphertext, iv, key, blocksize)
67
input_str, auth_tag = plaintext.split(":")
68
if cbc_mac_auth(input_str, iv, mac_key, blocksize, auth_tag):
69
print "Plaintext: ", input_str
70
else:
71
return "Verification failed, so nothing for you"
72
73
str1 = mac_then_encrypt("testplaintext", iv, key, mac_key, blocksize)
74
print str1
75
print auth_check(str1, iv, key, mac_key, blocksize)
76