Sunday, October 11, 2009

HMAC SHA Signatures using Python for Amazon webservices

Ive recently been working on the Amazon Product Advertising APIs to get some information from Amazon and display it to my users in a different format.

Since Django is such a wonderful framework, I decided to do this using app using Django. The Amazon Product Advertising documentation has examples for Java, C# and PHP, but not much help for Python. There isnt anything unique to Python as the calls are all either REST based or SOAP based, but there was one part that was tricky -- The HMAC SHA Signatures required for REST requests.

For starters, HMAC is abbreviation for keyed-Hash Message Authentication Code. For more information about HMAC, look up the RFC or the wikipedia entry. There is enough information in the documentation about how to make a REST request but none whatsoever about creating the HMAC based signature.

So, after some debugging and browsing through the forums, here is a snippet that will show how to create a HMAC-SHA based signature that you can use with AWS.

In the below code, its assumed that you followed this doc upto Step 7 since there is nothing thats specific to any programming language.

import hmac
import haslib
import base64
import urllib
.....
AWS_SECRET_KEY=
.....
request = """
Build request as shown in the above link till Step 7
"""
h = hmac.new(AWS_SECRET_KEY, request, hashlib.sha256)
signature = base64.b64encode(h.digest())
request = "%s&Signature=%s" %(request,urllib.quote(sig))
...
rest_output = urllib.urlopen('https://ecs.amazonaws.com/onca/xml?%s' %(request)).read()
...



The line for urllib.quote is required because Amazon wants us to quote the output that is gotten from HMAC based signature (Step 9 in the above document).

Hope it helps in doing a Python based HMAC-SHA signature generation for AWS.

1 comment:

  1. Thank you for this post. I was having a similar issue using web2py and you post cleared it up. The wording in the aws docs is quite confusing.

    Cheers...

    ReplyDelete