-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathhmac.py
48 lines (41 loc) · 1.41 KB
/
hmac.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
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives import hmac
from ..exception import Unsupported
from . import Signer
class HMACSigner(Signer):
def __init__(self, algorithm="SHA256"):
if algorithm == "SHA256":
self.algorithm = hashes.SHA256
elif algorithm == "SHA384":
self.algorithm = hashes.SHA384
elif algorithm == "SHA512":
self.algorithm = hashes.SHA512
else:
raise Unsupported("algorithm: {}".format(algorithm))
def sign(self, msg, key):
"""
Create a signature over a message as defined in RFC7515 using a
symmetric key
:param msg: The message
:param key: The key
:return: A signature
"""
h = hmac.HMAC(key, self.algorithm())
h.update(msg)
return h.finalize()
def verify(self, msg, sig, key):
"""
Verifies whether sig is the correct message authentication code of data.
:param msg: The data
:param sig: The message authentication code to verify against data.
:param key: The key to use
:return: Returns true if the mac was valid otherwise it will raise an
Exception.
"""
try:
h = hmac.HMAC(key, self.algorithm())
h.update(msg)
h.verify(sig)
return True
except:
return False