Created
November 27, 2014 10:38
-
-
Save danigm/bfd49f2e3e940dabc61b to your computer and use it in GitHub Desktop.
Agora HMAC generation and verification in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import hmac | |
import datetime | |
import time | |
KEY = b'123' | |
def genhmac(msg): | |
h = hmac.new(KEY, msg.encode('utf-8'), "sha256") | |
return 'khmac:///sha256;' + h.hexdigest() + '/' + msg | |
def verifyhmac(msg): | |
msg = msg[len('khmac:///'):] | |
digest, msg = msg.split(';') | |
orig_hmac, msg = msg.split('/') | |
h = hmac.new(KEY, msg.encode('utf-8'), digest) | |
valid = hmac.compare_digest(h.hexdigest(), orig_hmac) | |
t = msg.split(':')[-1] | |
n = datetime.datetime.now() | |
d = datetime.datetime.fromtimestamp(int(t)) | |
d = d + datetime.timedelta(seconds=5) | |
valid = valid and d > n | |
return valid | |
timestamp = int(datetime.datetime.now().timestamp()) | |
h = genhmac("danigm:vote:primariaspodemos:" + str(timestamp)) | |
print(h) | |
print(verifyhmac(h)) | |
time.sleep(6) | |
print(verifyhmac(h)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment