7

I am trying to compute an HMAC signature in Google Apps Script, but the documentation isn't 100% clear on how I need to pass in the parameters, and I have been unable to get the expected output.


To determine if I am getting correct output, I am comparing the result against known-good PHP code. That code is:

$key = "a2V5"; # this is "key" base64-encoded
$value = "test";
$result = base64_encode(hash_hmac('sha512', $value, base64_decode($key), true));

My code in Google Apps Script is:

key = "a2V5"; // this is "key" base64-encoded
value = "test";
result = Utilities.base64Encode(Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, value, Utilities.base64Decode(key)));

The output I expected to receive was:

KHoPuJp/vfpbVThjaRjlN6W4MGXk/zMSaLeqoRXd4EepsPT7W4KGCPwLYyfxAFX3Y3sFjp4Nu55piQGj5t1GHA==

But what I got instead was:

mGXJ3X/nH5ZIFUAPtf1PsViY50pD3cfU7J8w2KAIEAqrAgZ3dpKcuy5V1yvH4/C5n1C9rFFsKc2JKHTwUqPscQ==

What did I screw up here?

Michael Hampton
  • 9,737
  • 4
  • 55
  • 96

1 Answers1

7

I reviewed your code and there is one thing which caught my eye:

Utilities.base64Decode(key) method returns Byte[] Utilities.computeHmacSignature(macAlgorithm, value, key) accepts 3 parameters. value and key are of type string.

Maybe this is the issue. Why don't you try something like the following and check results then:

key = "a2V5"; // this is "key" base64-encoded
clearKey = "key";
value = "test";
result = Utilities.base64Encode(Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, value, clearKey));

I check Google Apps Script here.

Tom
  • 26,212
  • 21
  • 100
  • 111
  • This gives the correct result. Though it means I have to go report a bug in the API, which is another story... – Michael Hampton Dec 22 '12 at 22:42
  • If you need to accept base64-encoded input, you can take the byte array output and loop over it using `String.fromCharCode` to build it back into a string. – John Flatness Dec 22 '12 at 22:48
  • Oh, that hurts my head. I'll probably do that, but it would be nice if Google would do things right the first time... – Michael Hampton Dec 22 '12 at 22:51
  • 2
    For future reference, I submitted a [bug report](http://code.google.com/p/google-apps-script-issues/issues/detail?id=2227) to Google, and wound up using [jsSHA](http://caligatio.github.com/jsSHA/) in the project instead of Google's broken `Utilities.computeHmacSignature` method. – Michael Hampton Jan 03 '13 at 01:19
  • 1
    Miachael's suggestion of jsSHA works perfectly. I'll add that using a library in Google Scripts is counter-intuitive. Just paste `src/sha256.js` into a new file in your script and use `jsSHA` directly, without `require` and without using Google's library interface. Also, the bug report is still unresolved. – Andy Jul 04 '17 at 04:12