Skip to content

Instantly share code, notes, and snippets.

@tjnh05
Forked from binaryatrocity/hmac-sha1.py
Created January 14, 2020 14:35
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 tjnh05/7b407f09155fcdd58f9f8f822a4f48fa to your computer and use it in GitHub Desktop.
Save tjnh05/7b407f09155fcdd58f9f8f822a4f48fa to your computer and use it in GitHub Desktop.
HMAC-SHA1 Python example
from sys import argv
from base64 import b64encode
from datetime import datetime
from Crypto.Hash import SHA, HMAC
def create_signature(secret_key, string):
""" Create the signed message from api_key and string_to_sign """
string_to_sign = string.encode('utf-8')
hmac = HMAC.new(secret_key, string_to_sign, SHA)
return b64encode(hmac.hexdigest())
def create_token(access_key):
string_to_sign = "POST\n"+\
"application/x-www-form-urlencoded\n"+\
datetime.utcnow().strftime("%Y-%m-%dT%H:%M")
user_secret_key = access_key # Should be looked up based on access_key
hmac = create_signature(access_key, string_to_sign)
signature = "AUTH:" + access_key + ":" + hmac
return signature
def authenticate_signed_token(auth_token):
""" Take token, recreate signature, auth if a match """
lead, access_key, signature = auth_token.split(":")
if lead.upper() == "AUTH":
our_token = create_token(access_key).split(":", 1)[-1]
return True if signature == our_token else False
if __name__ == "__main__":
print create_token('secret_api_key')
print authenticate_signed_token(argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment