views:

32

answers:

1

Trying to get started with Amazon SNS. API is very simple REST. I seem to be hung up on the signature part of the call. The API example is:

http://sns.us-east-1.amazonaws.com/
?Subject=My%20first%20message
&TopicArn=arn%3Aaws%3Asns%3Aus-east-1%3A698519295917%3AMy-Topic
&Message=Hello%20world%21
&Action=Publish
&SignatureVersion=2
&SignatureMethod=HmacSHA256
&Timestamp=2010-03-31T12%3A00%3A00.000Z
&AWSAccessKeyId=AKIAJHS4T6XPF7XIURNA
&Signature=9GZysQ4Jpnz%2BHklqM7VFTvEcjR2LIUtn6jW47054xxE%3D

I've been following the API docs for signatures, so I'm trying:

from time import strftime,gmtime,time
import urllib2
import hmac
import hashlib
import base64
import string

def publichSNSMsg(Subject,TopicArn,Message,AWSAccessKeyId,privatekey):
  #http://docs.amazonwebservices.com/AWSSimpleQueueService/2008-01-01/SQSDeveloperGuide/
  amzsnshost = 'sns.us-east-1.amazonaws.com'
  values = {'Subject' : Subject,
            'TopicArn' : TopicArn,
            'Message' :Message,
            'Timestamp' : strftime("%Y-%m-%dT%H:%M:%S.000Z", gmtime(time())),
            'AWSAccessKeyId' : AWSAccessKeyId,
            'Action' : 'Publish',
            'SignatureVersion' : '2',
            'SignatureMethod' : 'HmacSHA256',
            }

  amazquote=lambda v: urllib2.quote(v).replace('%7E','~')
  cannqs=string.join(["%s=%s"%(amazquote(key),amazquote(values[key])) for key in sorted(values.keys(),key=str.lower)],'&')
  string_to_sign=string.join(["GET",amzsnshost,"/",cannqs],'\n')

  sig=base64.encodestring(hmac.new(privatekey,string_to_sign,hashlib.sha1).digest())
  querystring = "%s&Signature=%s"%(cannqs,amazquote(sig))
  url="http://%s/?%s"%(amzsnshost,querystring)

  try:
    return urllib2.urlopen(url).read()
  except urllib2.HTTPError, exception:
    return "Error %s (%s):\n%s"%(exception.code,exception.msg,exception.read())

And getting back:

<ErrorResponse xmlns="http://sns.amazonaws.com/doc/2010-03-31/"&gt; 
  <Error> 
    <Type>Sender</Type> 
    <Code>SignatureDoesNotMatch</Code> 
    <Message>The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.</Message> 
  </Error> 
  <RequestId>8d6e5a41-dafb-11df-ac33-f981dc4e6c50</RequestId> 
</ErrorResponse> 

Any ideas?

A: 

Aw, it was simple!

Keys in the query string were supposed to be byte-order sorted, not case-insensitive sorted (that was for version 1 signatures).

Slightly updated (and now correct) code is available on gist.

Kyle Fritz
Also there's a very complete python AWS library called [boto](http://github.com/boto/boto).
Kyle Fritz