Binary Output from Google Script HMAC encription

不羁岁月 提交于 2019-12-08 21:36:38

问题


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


回答1:


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);



回答2:


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



来源:https://stackoverflow.com/questions/17160896/binary-output-from-google-script-hmac-encription

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!