HMAC in Node.js crypto vs. Google Apps Script (GAS)

陌路散爱 提交于 2019-12-01 04:43:44

Utilities.base64Decode() returns a byte array not a string. You can create a blob from the byte array and then get it as a string restoring the original encoded string.

var secret = Utilities.base64Decode(key);
secret = Utilities.newBlob(secret).getDataAsString();

Try this example. I replaced your key with a new base64 encoded string and converted b64-decoded outputs to strings:
In node:

var key = "VEhJUyBJUyBBIFNUUklORw==";
//var key = "JOLDQW5wVIdwvHbhSDCktxhfwpgtxlAH+DG5EPoeDT8aPGSDYYh5U6QjbASUhvztjGPgA/Ue2x8QKwUklX7+Xw==";
var secret = new Buffer(key, "base64").toString();
var message = "message";
var crypto = require("crypto");
var hmac = new crypto.createHmac("sha512", secret);
var signature = hmac.update(message).digest("base64");
console.log(signature);

In GAS:

//var key = "JOLDQW5wVIdwvHbhSDCktxhfwpgtxlAH+DG5EPoeDT8aPGSDYYh5U6QjbASUhvztjGPgA/Ue2x8QKwUklX7+Xw==";
var key = "VEhJUyBJUyBBIFNUUklORw=="
var message = "message";
var secret = Utilities.base64Decode(key);
secret = Utilities.newBlob(secret).getDataAsString();
var hmac = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, secret);
var signature = Utilities.base64Encode(hmac);
Logger.log(signature);

both return the signature:

a9Jk2YQsKC164zEUoVChIpyfnEUZLj+Sj1mCAqs+jhDFvOliTupIfV+D6CNtaQGhQvAO40FZLhvYGubt1R5jQA==

But if I put your key back in the signatures again stop matching.

Tomáš Klíma

Aditional findings:

The results are the same form both of codes when it is used another key - as Spencer wrote. But there is yet another strange thing. Let's use Spencer's key to be sure both of codes will work. When we want to sign message with non-ASCII characters, e.g. "Tomáš", the codes will produce different results too!

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