Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm in ruby
Asked Answered
E

3

10

I was going through the Amazon Product Advertising API REST signature docs and I got stuck at #8

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.

Ecbatana answered 17/5, 2013 at 0:8 Comment(0)
E
15

I managed to get it on one more try with the help of Calculating a SHA hash with a string + secret key in python.

The following creates the correct signature:

require 'openssl'

secret_key = '1234567890'
query = 'AWSAccessKeyId=AKIAIOSFODNN7EXAMPLE&ItemId=0679722769&Operation=ItemLookup&ResponseGroup=ItemAttributes%2COffers%2CImages%2CReviews&Service=AWSECommerceService&Timestamp=2009-01-01T12%3A00%3A00Z&Version=2009-01-06'
data = ['GET', 'ecs.amazonaws.com', '/onca/xml', query].join("\n")
sha256 = OpenSSL::Digest::SHA256.new
sig = OpenSSL::HMAC.digest(sha256, secret_key, data)
signature = Base64.encode64(sig)
Ecbatana answered 17/5, 2013 at 0:8 Comment(2)
The url webservices.amazon.com has changed to ecs.amazonaws.com and you must update it in order to generate a valid signature.Undeniable
@HippieBandJam i assume you mean just the url, but would you mind editing my answer?Ecbatana
A
2

Adding to AJcodez answer:

I would do:

...
signature_raw = Base64.strict_encode64(sig)
signature     = CGI::escape(signature_raw)

encode64adds a newline at the end, strict_encode64() does not.

https://mcmap.net/q/134312/-strange-n-in-base64-encoded-string-in-ruby

Amazon wants you to "URL encode the plus (+) and equal (=) characters in the signature" #9 - won't work now if you don't.

http://docs.aws.amazon.com/AWSECommerceService/latest/DG/rest-signature.html#rest_detailedexample

Acrid answered 11/12, 2014 at 22:51 Comment(0)
M
1

You can calculate a keyed-hash message authentication code (HMAC-SHA256) signature with your secret access key by using cryptoJs

First install cryptoJs locally in your system by typing

npm install crypto-js

to install it globally you node a flag -g to the above command. Then add this code and run it.

var CryptoJS = require("crypto-js");

// Calculate an RFC 2104-compliant HMAC with the SHA256 hash algorithm

var exampleString = 
    "GET\n" +
    "webservices.amazon.com\n" +
    "/onca/xml\n" + 
    "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";

var signature = CryptoJS.HmacSHA256(exampleString, "1234567890");

console.log("test signature", signature.toString(CryptoJS.enc.Base64));
Mcquiston answered 6/7, 2018 at 12:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.