如何从Google Apps脚本的computeHmacSha256Signature方法获取Hex值?

时间:2016-12-19 23:25:32

标签: google-apps-script

我在下面阅读了MD5的解决方案,但我无法理解它 get back a string representation from computeDigest(algorithm, value) byte[]

我想用HMAC-SHA256哈希创建API签名。

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

但它返回字节数组[42,-8,-47,-21,..],它不能直接用作API签名。 有没有一种从方法中获取Hex值的简单方法?还是转换?

2 个答案:

答案 0 :(得分:7)

我应用方法you linked to并获取:

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

所以这是一个测试功能:

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
}

答案 1 :(得分:2)

加上高尔夫:

Utilities.computeHmacSha256Signature(message, secret)
  .map(function(chr){return (chr+256).toString(16).slice(-2)})
  .join('')