Go4Expert

Go4Expert (http://www.go4expert.com/)
-   Python (http://www.go4expert.com/articles/python-tutorials/)
-   -   Introduction to HMAC & Using in Python (http://www.go4expert.com/articles/introduction-hmac-using-python-t29628/)

pradeep 23Apr2013 17:46

Introduction to HMAC & Using in Python
 
HMAC stands for Hash-base Message Authentication Code, it is key based message digest algorithm which can be used for verifying the integrity of the message (i.e. the original message from which the hash is generated) or to verify the authenticity of the sender of the message or both. Nowadays, HMAC is being widely used in various systems & domains, like server-to-server communications, Web Service APIs, etc. A well known use of HMAC is in Amazon's AWS API calls where the signature is generated using HMAC.

HMAC can use a variety of hashing algorithms, like MD5, SHA1, SHA256, etc. HMAC function is not very processing intensive, so it has been widely accepted, and it is relatively easy to implement in mobile & embedded devices too while maintaining decent security.

Using HMAC in Python



Since Python version 2.2 the HMAC module comes with Python installation, and the hashing library hashlib comes with the Python installation from version 2.5 onwards, in case you are having Python versions lesser than earlier mentioned, you'll need to manually install the HMAC/hashlib libraries.

Once you are all set, creating the HMAC digest is pretty simple, follow the next code example where we'll generate a HMAC-MD5 digest with Python code:

Code: Python

import hmac
from hashlib import md5

key = 'HAHGDSHHHKMYKEY'

h = hmac.new(key,'',md5)

## add content
h.update('Asha')

## print the HMAC digest
print h.hexdigest()


That was easy, now I'll demonstrate a real-world example of generating Amazon S3 sharing file URL:

Code: Python

import hmac
from hashlib import sha1
import base64
import time
import urllib

s3_path = '/g4ebucket/data.tgz'
s3_access_key = 'hsjahhjj33'
s3_secret_key = 'kAJSJSDhAKJSj/kajskSAKj/='
s3_expiry = time.time() + 60 * 10 ## 10 minutes

str_to_sign = "GET\n\n\n%s\n%s" % s3_expiry,s3_path

h = hmac.new(s3_secret_key,'',hashlib.sha())

h.update(str_to_sign)

## read more about signing method: http://docs.aws.amazon.com/AmazonS3/latest/dev/RESTAuthentication.html
signature = urllib.urlencode( base64.b64encode( h.digest ) )

## print out the URL
print "http://s3.amazonaws.com%s?AWSAccessKeyId=%s&Expires=%s&Signature=%s" % s3_path, s3_access_key, s3_expiry, signature



All times are GMT +5.5. The time now is 11:53.