Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Output from Google Script HMAC encription

I am current working with Google Apps script and am attempting to write & sign an HTTP request to AWS CloudWatch.

On the Amazon API documentation here regarding how to create a signing key, they use pseudo to explain that the HMAC algorithm is to return binary format.

HMAC(key, data) represents an HMAC-SHA256 function 
that returns output in binary format.

Google apps script offers a method to do such a hash,

Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256,
                                            data,
                                            key);

but the return type is always a byte array.

Byte[]

How do I convert the Byte[] to the binary data AWS wants? Or is there a vanilla javascript function I can use in Google Apps Script to compute the hash?

Thanks

like image 253
user2495753 Avatar asked Jun 18 '13 05:06

user2495753


2 Answers

I am quite sure it is a bug that Utilities.computeHmacSignature take key as an ASCII. But there was no way to parse byte[] to ASCII correctly in GAS

And the library writer is too stupid too just provide function which take key as byte[]

So I use this instead : http://caligatio.github.com/jsSHA/

Just copy SHA.js and SHA-256.js then it work fine

PS. it waste my time for whole 2 days so I'm very annoying

like image 78
Thaina Yu Avatar answered Nov 29 '22 21:11

Thaina Yu


The conversion from byte array to the binary data required should be simple:

kDate = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256,
             '20130618', 'AWS4' + kSecret);
kDate = Utilities.newBlob(kDate).getDataAsString();
kRegion = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, 
             'eu-west-1', kDate);

BUT you have to look onto this open issue in the bugtracker - there could be some issues in conversion.

maybe you could try to make a String.fromCharCode() loop and avoid negative numers:

kDateB = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256,
             '20130618', 'AWS4' + kSecret);
kDate = '';
for (var i=0; i<kDateB.length; i++)
  kDate += String.fromCharCode(kDateB[i]<0?256+kDateB[i]:0+kDateB[i]);
kRegion = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_256, 
             'eu-west-1', kDate);
like image 38
Taras Avatar answered Nov 29 '22 19:11

Taras