6

I read solution for MD5 below, but I could not quite get it.
get back a string representation from computeDigest(algorithm, value) byte[]

I'd like to create API signature with HMAC-SHA256 hash.

var date = new Date();
var nonce = Math.floor(date.getTime()/1000);
var url = "https://mysweet.com/api/accounts"
var secret = "my_secret";
var signature = Utilities.computeHmacSha256Signature(nonce+url, secret);

but it returns byte array [42, -8, -47, -21, ..], and it cannot be used as API signature directly. Is there a simple way to get a Hex value from the method? or conversion?

Community
  • 1
  • 1
M_Igashi
  • 475
  • 5
  • 9

3 Answers3

14

I applied the method you linked to and get:

var sig = signature.reduce(function(str,chr){
  chr = (chr < 0 ? chr + 256 : chr).toString(16);
  return str + (chr.length==1?'0':'') + chr;
},'');;

So here's a test function:

function testSig() {
  var date = new Date();
  var message = "Violets are red";
  var secret = "my_secret";
  var signature = Utilities.computeHmacSha256Signature(message, secret);
  var sig = signature.reduce(function(str,chr){
    chr = (chr < 0 ? chr + 256 : chr).toString(16);
    return str + (chr.length==1?'0':'') + chr;
  },'');
  Logger.log(sig); // fe70fa2e74b3ee0d67aa3c1d5c2844e558fea6802e8cfa58e5d4cbdf8bad25fe
  //output from http://www.freeformatter.com/hmac-generator.html#ad-output is:
  //                  fe70fa2e74b3ee0d67aa3c1d5c2844e558fea6802e8cfa58e5d4cbdf8bad25fe
}
Community
  • 1
  • 1
Peter
  • 5,501
  • 2
  • 26
  • 42
  • more than parfect!! Thank you Peter. I wonder why GAS returns byte[] from the method often used in signature generation..... – M_Igashi Dec 20 '16 at 01:01
7

Plus golf:

Utilities.computeHmacSha256Signature(message, secret)
  .map(function(chr){return (chr+256).toString(16).slice(-2)})
  .join('')
William Entriken
  • 37,208
  • 23
  • 149
  • 195
1
var date = new Date();
var nonce = Math.floor(date.getTime()/1000);
var url = "https://mysweet.com/api/accounts"
var secret = "my_secret";
var signature = Utilities.computeHmacSha256Signature(nonce+url, secret)
signature = signature.map(function(e) {return ("0" + (e < 0 ? e + 256 : e).toString(16)).slice(-2)}).join("");
Adrien82
  • 49
  • 4