I tried to make requests to Amazon AWIS, but I always get an error.
The official documentation is available here:
http://ift.tt/1qzyAk6
Making Requests > Calculating Signatures
Here is an official php file to make a request, and it worked:
http://ift.tt/1wFtqS8
I wrote the following code in node.js but it didn't work:
var key = "foo";
var host = "awis.amazonaws.com";
var query =
"Action=UrlInfo" +
"&AWSAccessKeyId=bar" +
"&Count=10" +
"&ResponseGroup=Rank" +
"&SignatureMethod=HmacSHA256" +
"&SignatureVersion=2" +
"&Start=1" +
"&Timestamp=2015-03-01T21%3A05%3A00.005Z" +
"&Url=stackoverflow.com";
var stringToSign =
"GET\n" +
host + "\n" +
"/\n" +
query;
log("stringToSign: " + stringToSign);
var signature = crypto.createHmac("sha256", key).update(stringToSign).digest('hex');
signature = new Buffer(signature).toString("base64");
console.log("signature: " + signature);
signature = encodeURIComponent(signature).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
console.log("enc signature: " + signature);
query += "&Signature=" + signature;
log("\n\nfinal query:\n" + query);
request.get({
url: "http://" + host + "/?" + query,
}, function(err, response, body) {
res.send(body);
});
Could somebody go through the PHP code and my code and check what could be different?
EDIT 1: I found out that the hmac function from php takes a fourth parameter:
hash_hmac('sha256', $sign, $this->secretAccessKey, true) // <- true param
which returns binary data instead of hex data.
I accordingly change my code from this to the other two following examples:
var signature = crypto.createHmac("sha256", key).update(stringToSign).digest("hex");
signature = signature.toString("base64");
Neither this
var signature = crypto.createHmac("sha256", key).update(stringToSign).digest("binary"); // <- notice "binary"
console.log(signature); // this returns some strange symbols in cmd, the same as in the php script, so this seems normal
signature = signature.toString("base64");
nor this
var signature = crypto.createHmac("sha256", key).update(stringToSign).digest("binary"); // <- notice "binary"
signature = (new Buffer(hmac, "binary")).toString("base64");
worked.
Aucun commentaire:
Enregistrer un commentaire