How do I get Google Apps Script to do SHA-256 encryption?

本秂侑毒 提交于 2020-12-04 08:57:54

问题


I need to encrypt strings with TEXT input, 1 round, HEX output, SHA-256 encryption. Which should be a string of characters of length 64.
Every SHA-256 encryption module I've tried in Google Apps Script docs returns a set of numbers. For example.

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

Outputs

[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]

I haven't seen anything in the docs or elsewhere that specifies every parameter I'm going for outlined above for GAS. I wouldn't mind a deeper explanation of putting it together from scratch if that is what is required. I'm encrypting info to send to Facebook for Offline Conversions for ads. How does Facebook decrypt the encrypted strings?
Google Apps Script docs
https://developers.google.com/apps-script/reference/utilities/utilities#computeHmacSha256Signature(String,String,Charset)


回答1:


̶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()returns an array of bytes (8-bit integers). If you want to convert that array to a string composed of hexadecimal characters you'll have to do it manually as follows:

/** @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("");


来源:https://stackoverflow.com/questions/59381945/how-do-i-get-google-apps-script-to-do-sha-256-encryption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!