[英]How do I get Google Apps Script to do SHA-256 encryption?
我需要使用 TEXT 輸入、1 輪、HEX 輸出、SHA-256 加密來加密字符串。 這應該是一個長度為 64 的字符串。
我在 Google Apps Script 文檔中嘗試過的每個 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)
̶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("");
這是生成 SHA-256 哈希作為十六進制字符串的一對函數:
function Sha256Hash(value) {
return BytesToHex(
Utilities.computeDigest(
Utilities.DigestAlgorithm.SHA_256, value));
}
function BytesToHex(bytes) {
let hex = [];
for (let i = 0; i < bytes.length; i++) {
let b = parseInt(bytes[i]);
if (b < 0) {
c = (256+b).toString(16);
} else {
c = b.toString(16);
}
if (c.length == 1) {
hex.push("0" + c);
} else {
hex.push(c);
}
}
return hex.join("");
}
事實證明, bytes[]
類型可用作普通Array
,因此我在編寫BytesToHex()
時利用了這BytesToHex()
。
一定有更優雅的方法,但我更進一步,並設法為調用 AWS API 派生了正確的簽名:
// Google Apps Script version of https://docs.aws.amazon.com/general/latest/gr/signature-v4-examples.html#signature-v4-examples-javascript
function getSignatureKey(key, dateStamp, regionName, serviceName) {
const kDate = Utilities.computeHmacSha256Signature(dateStamp, "AWS4" + key);
Logger.log("kDate = '" + BytesToHex(kDate) + "'");
const kRegion = Utilities.computeHmacSha256Signature(Utilities.newBlob(regionName).getBytes(), kDate);
Logger.log("kRegion = '" + BytesToHex(kRegion) + "'");
const kService = Utilities.computeHmacSha256Signature(Utilities.newBlob(serviceName).getBytes(), kRegion);
Logger.log("kService = '" + BytesToHex(kService) + "'");
const kSigning = Utilities.computeHmacSha256Signature(Utilities.newBlob("aws4_request").getBytes(), kService);
Logger.log("kSigning = '" + BytesToHex(kSigning) + "'");
return kSigning;
}
function Sha256Hmac(value, key) {
return BytesToHex(Utilities.computeHmacSha256Signature(Utilities.newBlob(value).getBytes(), key));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.