del*_*ach 1 javascript base64 hmac node.js google-apps-script
Given this code in nodejs:
const crypto = require('crypto');
const message = 'message to sign';
const secret = 'mysecret';
const signature = crypto.createHmac('sha256', secret).update(message).digest('hex');
console.log(signature);
Run Code Online (Sandbox Code Playgroud)
The output is 40d4c57eed56968de0f3a22e73ebf8abc6ab4c38bba95fd2c85dd4dc90bf36b9
With the help of the answers here, I have exactly replicated this behavior in Google Apps Script, with this function:
//conversion from byte array taken from: /sf/answers/1955342161/
function makeHmacSignature(macAlg, message, secret) {
return Utilities.computeHmacSignature(macAlg, message, secret).reduce(function(str,chr){
chr = (chr < 0 ? chr + 256 : chr).toString(16);
return str + (chr.length==1?'0':'') + chr;
},'');
}
Run Code Online (Sandbox Code Playgroud)
HOWEVER, suppose the signing is changed slightly, such that the secret is a base64 encoded string, and we expect the digest in base64. In the nodejs code, the changes are trivial:
const crypto = require('crypto');
const message = 'message to sign';
const secret = 'mysecret';
const decodedSecret = Buffer(secret, 'base64');
const signature = crypto.createHmac('sha256', decodedSecret).update(message).digest('base64');
console.log(signature);
Run Code Online (Sandbox Code Playgroud)
Giving the output bBLhyGY61BPEbPiFKknX1g9eXv9r98uvwwgVy7YMYDY=
I've been trying for hours, I cannot figure out how to replicate this behavior in Google Apps Script!
Google Apps Script 实际上有一个实用功能。
请参阅:https : //developers.google.com/apps-script/reference/utilities/utilities#computehmacsha256signaturevalue-key
所以代替
const signature = crypto.createHmac('sha256', secret).update(message).digest('hex');
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
var byteSignature = Utilities.computeHmacSha256Signature(message, secret);
// convert byte array to hex string
var signature = byteSignature.reduce(function(str,chr){
chr = (chr < 0 ? chr + 256 : chr).toString(16);
return str + (chr.length==1?'0':'') + chr;
},'');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2273 次 |
| 最近记录: |