Google Apps脚本相当于PHP的hash_hmac()和RAW BINARY输出?

时间:2017-09-07 21:33:50

标签: javascript php google-apps-script base64 hmac

我必须使用hash_hmac连接到API。在hash_hmac的PHP文档中,第四个参数bool $ raw_output控制输出是原始二进制数据(true)还是小写hexits(false)。我的程序只需将该参数设置为true即可在PHP中运行。

这适用于PHP:

$signature = base64_encode(hash_hmac('SHA256', $signature_string, $private_key, true))

在Google Apps中我不能使用任何javascript库(或者我可以吗?)但是有这个功能:Utilities.computeHmacSha256Signature https://developers.google.com/apps-script/reference/utilities/utilities#computehmacsha256signaturevalue-key

但是,它没有PHP的“true”选项,因此它不会输出原始二进制数据。

如何使用Google Apps获得与PHP相同的价值?

这就是我在Google Apps中的功能,但显然它不会输出原始二进制数据:

var signature = Utilities.computeHmacSha256Signature(signature_string, private_key);

我确实找到了将响应转换为十六进制的方法(PHP相当于FALSE而不是TRUE,但这并没有让我更接近解决方案。

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

1 个答案:

答案 0 :(得分:0)

对我有用的只是将这些脚本直接复制到Google Apps中:

https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/hmac-sha256.js https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/components/enc-base64-min.js

然后使用:

var hash = CryptoJS.HmacSHA256(signature, private_key);
var base64 = hash.toString(CryptoJS.enc.Base64);

小提琴: http://jsfiddle.net/c5r78fzm/