首页 > 解决方案 > 如何让 Google Apps 脚本进行 SHA-256 加密?

问题描述

我需要使用 TEXT 输入、1 轮、HEX 输出、SHA-256 加密来加密字符串。这应该是长度为 64 的字符串。
我在 Google Apps 脚本文档中尝试过的每个 SHA-256 加密模块都会返回一组数字。例如。

function SHA256() {
    var signature = Utilities.computeHmacSha256Signature("this is my input",
                                                 "my key - use a stronger one",
                                                 Utilities.Charset.US_ASCII);
Logger.log(signature);
    }

输出

[53, -75, -52, -25, -47, 86, -21, 14, -2, -57, 5, -13, 24, 105, -2, -84, 127, 115, -40, -75, -93, -27, -21, 34, -55, -117, -36, -103, -47, 116, -55, -61]

我没有在文档或其他地方看到任何指定我在上面为 GAS 概述的每个参数的内容。如果需要的话,我不介意从头开始对它进行更深入的解释。我正在加密信息以发送到 Facebook 以进行广告的离线转换。Facebook 如何解密加密的字符串?
Google Apps 脚本文档
https://developers.google.com/apps-script/reference/utilities/utilities#computeHmacSha256Signature(String,String,Charset)

标签: javascriptgoogle-apps-scriptsha256sha

解决方案


̶U̶t̶i̶l̶i̶t̶i̶e̶s̶.̶c̶o̶m̶p̶u̶t̶e̶H̶m̶a̶c̶S̶h̶a̶2̶5̶6̶S̶i̶g̶n̶a̶t̶u̶r̶e̶ Utilities.computeDigest()返回一个字节数组(8 位整数)。如果您想将该数组转换为由十六进制字符组成的字符串,您必须手动执行以下操作:

/** @type Byte[] */
var signature = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, value);

/** @type String */
var hexString = signature
    .map(function(byte) {
        // Convert from 2's compliment
        var v = (byte < 0) ? 256 + byte : byte;

        // Convert byte to hexadecimal
        return ("0" + v.toString(16)).slice(-2);
    })
    .join("");

推荐阅读