JackyJohnson
JackyJohnson

Reputation: 3126

Cannot generate Amazon product API signature using Golang

Help. I can't get the right signature using the test parameters provided by Amazon and Go.

My signature hash function is as follows. I use SHA-256 and base64 encoding as per Amazon documentation.

func HashSignature(str string, secret string) string {
  mac := hmac.New(sha256.New, []byte(secret))
  _, err := mac.Write([]byte(str))
  if err != nil {   return "" }

  hash := base64.StdEncoding.EncodeToString(mac.Sum(nil))
  hash = url.QueryEscape(hash)
  return hash
}

My signature test function is as follows. I use the canonical string below in Ruby code and it generates the correct expected signature. So the problem seems to be with the output of my HashSignature() function, but I don't see what I'm doing wrong there.

func TestAmazonSignature(t *testing.T) {
/* here is the canonical string from Amazon documentation which should yield the expected signature below
GET
webservices.amazon.com
/onca/xml
AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&AssociateTag=mytag-20&ItemId=0679722769&Operation=ItemLookup&ResponseGroup=Images%2CItemAttributes%2COffers%2CReviews&Service=AWSECommerceService&Timestamp=2014-08-18T12%3A00%3A00Z&Version=2013-08-01
*/
  SECRET_KEY := "1234567890"
  CANONICAL_STR := "GET\nwebservices.amazon.com\n/onca/xml\nAWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&AssociateTag=mytag-20&ItemId=0679722769&Operation=ItemLookup&ResponseGroup=Images%2CItemAttributes%2COffers%2CReviews&Service=AWSECommerceService&Timestamp=2014-08-18T12%3A00%3A00Z&Version=2013-08-01"

  EXPECTED := "j7bZM0LXZ9eXeZruTqWm2DIvDYVUU3wxPPpp%2BiXxzQc%3D"

  if RESULT := HashSignature(CANONICAL_STR, SECRET_KEY); RESULT != EXPECTED {
    t.Errorf("\nEXPECTED:\n%v\nRESULT:\n%v", EXPECTED, RESULT)
  } else { fmt.Println("TestAmazonSignature: Signature: OK") }
}

Here's a playground link with all this code.

Upvotes: 0

Views: 286

Answers (1)

Michael Xu
Michael Xu

Reputation: 141

Looks fine to me, try running:

https://play.golang.org/p/w0mQAYx2GQ

I added necessary imports and a main function

Upvotes: 1

Related Questions