-
Notifications
You must be signed in to change notification settings - Fork 0
/
HmacKeccak.py
109 lines (86 loc) · 3.08 KB
/
HmacKeccak.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
""" Task A: validate
Algorithm:
1. Retreive key
2. Compute MAC (hash of key and message - Keccak)
3. Increment counter
"""
""" Task A: generate
Algorithm:
1. Increment counter
2. Retrieve key
3. Compute MAC (hash of key with message content)
4. Compare received MAC with computed MAC
"""
"""
This module will provide an interface for the hmac function
using keccak
"""
import sys
import hashlib
if sys.version_info < (3,4):
import sha3
import hmac
from ChangeKey import ChangeKey
class HmacKeccak:
"""A class to abstract MAC generation and validation"""
counter =0 #the nonce
key = 0 #symmetric key
def __init__(self,key,ctr=None):
"""Create an instance of HMAC Keccak
key: symmetric key
ctr: initialVector (optional default =0)
"""
if ctr is None:
self.counter = 0
else:
self.counter =ctr
self.key = key;
def generateTag(self,message):
"""Generate a tag, increment a counter"""
message = str(self.counter) + message;
self.counter = self.counter + 1;
return self.generateTagStateless(message)
def generateTagStateless(self,message):
"""Generate a tag without incrementing the internal counter
useful for verification of a MAC"""
tag = hmac.new(key,message,hashlib.sha3_256).digest();
return tag
def verifyTag(self,message,tag):
"""Validate a MAC and update counter to synchronize"""
message = str(self.counter) + message;
if(self.verifyTagStateless(message,tag)):
self.counter = self.counter +1;
return True
else:
return False
def verifyTagStateless(self,message,tag):
"""Verify if a tag is authentic
useful for checking
"""
return self.generateTagStateless(message) == tag
def new(key,ctr=None):
return HmacKeccak(key,ctr)
if(__name__ == '__main__'):
"""check if consistency requirement of MAC still holds"""
key = "98fkj998w8uhwluww0"
message = "ID=0,Data=fireOnEngine3"
hk = new(key);
key_changer = ChangeKey()
for i in range(64): # Should have two different keys
if i > 0:
key_changer.perform_change(hk)
if key != key_changer.current_key:
key = key_changer.current_key
hk = new(key, hk.counter)
tag =hk.generateTag(message)
statefulMessage = str(i)+message;
consistent = hk.verifyTagStateless(statefulMessage,tag)
print "Consistent Stateful generate and verify: " + str(consistent)
tag=hk.generateTagStateless(message)
consistent = hk.verifyTagStateless(message,tag)
print "Consistent Stateless generate and verify: " + str(consistent)
sender = new(key,0)
receiver = new(key,0)
tag =sender.generateTag(message)
consistent = receiver.verifyTag(message,tag)
print "Consistent Stateful generate and verify: " + str(consistent)