Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
ashutosh1206
GitHub Repository: ashutosh1206/crypton
Path: blob/master/Authenticated-Encryption/AE-with-MACs/Encrypt-then-MAC/encrypt-then-mac.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
32
33
def encrypt(input_str, iv, key, blocksize):
34
input_str = pad(input_str, blocksize)
35
obj1 = AES.new(key, AES.MODE_CBC, iv)
36
ciphertext = obj1.encrypt(input_str)
37
return ciphertext
38
39
def decrypt(ciphertext, iv, key, blocksize):
40
obj1 = AES.new(key, AES.MODE_CBC, iv)
41
plaintext = obj1.decrypt(ciphertext)
42
return unpad(plaintext)
43
44
def encrypt_then_mac(input_str, iv, key, mac_key, blocksize):
45
ciphertext = encrypt(input_str, iv, key, blocksize)
46
tag = cbc_mac_gen(ciphertext, iv, mac_key, blocksize)
47
return ciphertext.encode("hex") + ":" + tag.encode("hex")
48
49
def auth_check(session_cookie, iv, key, mac_key, blocksize):
50
ciphertext, tag = session_cookie.split(":")
51
ciphertext = ciphertext.decode("hex")
52
tag = tag.decode("hex")
53
if cbc_mac_gen(ciphertext, iv, mac_key, blocksize) == tag:
54
print "Authentication Successful"
55
return decrypt(ciphertext, iv, key, blocksize)
56
else:
57
print "Authentication Failed"
58
return 0
59
60
str1 = encrypt_then_mac("testplaintext", iv, key, mac_key, 16)
61
print str1
62
print auth_check(str1, iv, key, mac_key, blocksize)
63