【问题标题】:Google Apps script equivalent of PHP's hash_hmac() with RAW BINARY output?具有原始二进制输出的 PHP 的 hash_hmac() 等效的 Google Apps 脚本?
【发布时间】:2017-09-07 21:33:49
【问题描述】:

我必须使用 hash_hmac 连接到 API。在 hash_hmac 的 PHP 文档中,第四个参数 bool $raw_output 控制输出是原始二进制数据 (true) 还是小写十六进制 (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;
},'');

【问题讨论】:

  • 也许发布一些 PHP 和 GAppScript 的示例输出可以帮助我们解决问题?
  • 我只是在这里猜测,但是将Utilities.computeHmacSha256Signature() 生成的字节数组输入Utilities.newBlob() 是否满足您的需求?
  • 虽然,查看stackoverflow.com/questions/17160896/… 会表明这不是解决方案...

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


【解决方案1】:

对我有用的只是将这些脚本直接复制到 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/

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 2011-05-24
    • 2019-11-07
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多