Can you explain the difference between creating an HmacSha512 signature using the Node.JS Crypto module and Google Apps Script?
Code 1 - Node.JS
var secret = "my secret";
var message = "message";
var crypto = require("crypto");
var hmac = new crypto.createHmac("sha512", secret);
var signature = hmac.update(message).digest("base64");
console.log(signature);
Code 1 - Google Apps Script
var secret = "my secret";
var message = "message";
var signature = Utilities.base64Encode(Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, secret));
Logger.log(signature);
Both codes generate an identical signature:
g4fZkM2XGNjhti9Wah3TU2/rvmxbL3nk4F3ZLljpED23oQ7Y7dtVmVKprQKuzyt0B4Spo214isWCvnoXXVTS8g==
But the problem arises when we have a secret in the form of a base64 encoded key. So, the first step we must take is to prepare a secret. Change the code:
Code 2 - Node.JS
var key = "JOLDQW5wVIdwvHbhSDCktxhfwpgtxlAH+DG5EPoeDT8aPGSDYYh5U6QjbASUhvztjGPgA/Ue2x8QKwUklX7+Xw==";
var secret = new Buffer(key, "base64");
var message = "message";
var crypto = require("crypto");
var hmac = new crypto.createHmac("sha512", secret);
var signature = hmac.update(message).digest("base64");
console.log(signature);
Result:
GELSKf33zit7nIfjj8XH3wZIga/CSYuCU5oTGysqOg6C/wFggunw59wzc7Mr95XW/gZ8putB67AADqnP0gLdiw==
Code 2 - Google Apps Script
var key = "JOLDQW5wVIdwvHbhSDCktxhfwpgtxlAH+DG5EPoeDT8aPGSDYYh5U6QjbASUhvztjGPgA/Ue2x8QKwUklX7+Xw==";
var message = "message";
var secret = Utilities.base64Decode(key);
var signature = Utilities.base64Encode(Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, secret));
Logger.log(signature);
Result:
l11xAQ5C5ARx/r/pbNYpMKCqWOwIaxFTkfS9OXCwfUxv33y3gU/sL2vHueOxpkCKmF+lxIcFMYblwrvfWaTZkg==
The difference is probably related to the processing / decryption of the key (Buffer vs. Utilities.base64Decode). The version of Node.js is correct (it is tested on the server side).
How to decode and use a key using Google Apps Script?