Skip to content

Instantly share code, notes, and snippets.

@Xowap
Last active July 22, 2016 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Xowap/f295e0f7491cd12054d8e100a392e182 to your computer and use it in GitHub Desktop.
Save Xowap/f295e0f7491cd12054d8e100a392e182 to your computer and use it in GitHub Desktop.
# vim: fileencoding=utf-8 tw=100 expandtab ts=4 sw=4 :
import json
import hmac
from hashlib import sha256
from uuid import uuid4
from time import time
def force_bytes(s):
if isinstance(s, u''.__class__):
s = s.encode()
return s
def force_text(s):
if not isinstance(s, u''.__class__):
s = s.decode()
return s
def create_msg(email, secret):
secret = force_bytes(secret)
data = {
'email': email,
'nonce': u''.__class__(uuid4()),
'timestamp': time(),
}
msg = json.dumps(data).encode()
h = hmac.new(secret, msg, sha256)
return {
'msg': msg,
'sign': h.hexdigest(),
}
def nonce_was_used(nonce, validity):
# TODO implement using redis or whatever
return False
def check_msg(msg, sign, secret, ts_validity=300):
msg = force_bytes(msg)
sign = force_text(sign)
secret = force_bytes(secret)
data = json.loads(force_text(msg))
h = hmac.new(secret, msg, sha256)
now = time()
ts = float(data.get('timestamp', 0))
if nonce_was_used(data.get('nonce'), ts_validity) or \
not hmac.compare_digest(force_bytes(sign), force_bytes(h.hexdigest())) or \
ts + ts_validity < now:
return
return data.get('email')
if __name__ == '__main__':
params = create_msg('toto@toto.com', 'yolo')
print(check_msg(secret='yolo', **params))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment