Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Hex value from computeHmacSha256Signature method of Google Apps Script?

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?

like image 983
M_Igashi Avatar asked Dec 19 '16 23:12

M_Igashi


1 Answers

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
}
like image 148
Pete Avatar answered Sep 19 '22 14:09

Pete