Skip to content

Instantly share code, notes, and snippets.

@danigm
Created November 27, 2014 10:38
Show Gist options
  • Save danigm/bfd49f2e3e940dabc61b to your computer and use it in GitHub Desktop.
Save danigm/bfd49f2e3e940dabc61b to your computer and use it in GitHub Desktop.
Agora HMAC generation and verification in python
#!/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