Calculating a SHA hash with a string + secret key in python

mymmaster picture mymmaster · Aug 20, 2009 · Viewed 77.3k times · Source

Amazon Product API now requires a signature with every request which I'm trying to generate ushing Python.

The step I get hung up on is this one:

"Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm using the string above with our "dummy" Secret Access Key: 1234567890. For more information about this step, see documentation and code samples for your programming language."

Given a string and a secret key (in this case 1234567890) how do I calculate this hash using Python?

----------- UPDATE -------------

The first solution using HMAC.new looks correct however I'm getting a different result than they are.

http://docs.amazonwebservices.com/AWSECommerceService/latest/DG/index.html?rest-signature.html

According to Amazon's example when you hash the secret key 1234567890 and the following string

GET
webservices.amazon.com
/onca/xml
AWSAccessKeyId=00000000000000000000&ItemId=0679722769&Operation=I
temLookup&ResponseGroup=ItemAttributes%2COffers%2CImages%2CReview
s&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z&
Version=2009-01-06

You should get the following signature: 'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='

I am getting this: '411a59403c9f58b4a434c9c6a14ef6e363acc1d1bb2c6faf9adc30e20898c83b'

Answer

SilentGhost picture SilentGhost · Aug 20, 2009
import hmac
import hashlib
import base64
dig = hmac.new(b'1234567890', msg=your_bytes_string, digestmod=hashlib.sha256).digest()
base64.b64encode(dig).decode()      # py3k-mode
'Nace+U3Az4OhN7tISqgs1vdLBHBEijWcBeCqL5xN9xg='