Node.js Fiddle:
const crypto = require('crypto');
let secret = 'my_secret';
let message = 'my_message';
let signer = crypto.createHmac('sha512', secret)
const signature = signer.update(message).digest('base64');
console.log(signature);
//signature = DWpafZMnI4PT5v0jdidFtU5qoh3fsvUKnaOga/Y2Nzy/tvsx1F9p61SjE+hlRQ97y/LMmBkG39IyL5Ja46bJlw==
// ***** Use Hex Buffer instead of string - same result
let message_buffer = Buffer.from(message); //<Buffer 6d 79 5f 6d 65 73 73 61 67 65>
let signer_from_buffer = crypto.createHmac('sha512', secret)
const signature_from_buffer = signer_from_buffer.update(message_buffer).digest('base64');
console.log(signature_from_buffer);
// signature = DWpafZMnI4PT5v0jdidFtU5qoh3fsvUKnaOga/Y2Nzy/tvsx1F9p61SjE+hlRQ97y/LMmBkG39IyL5Ja46bJlw==
and in Google Apps Script:
var secret = 'my_secret';
var message = 'my_message';
var signature_hash = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message, secret);
var signature = Utilities.base64Encode(signature_hash);
Logger.log(signature);
//signature = DWpafZMnI4PT5v0jdidFtU5qoh3fsvUKnaOga/Y2Nzy/tvsx1F9p61SjE+hlRQ97y/LMmBkG39IyL5Ja46bJlw==
// Use Hex Array instead of string - different result
var message_buffer = ["6d", "79", "5f", "6d", "65", "73", "73", "61", "67", "65"];
var signature_hash_from_buffer = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message_buffer , secret);
var signature_from_buffer = Utilities.base64Encode(signature_hash_from_buffer );
Logger.log(signature_from_buffer );
//signature_from_buffer = gGK0Y/KytE+8ZKWs/og1VQ1wMdPnoFmJMCHGpKdi+QODFwykqvDK5qJwgzZrr1b1g5050j9r8jpfXlM2ZA+3qQ==
So I know my Crypto process is working correctly. The problem is, I am starting from the Hex Array, so I want to be able to get the same result. I can't figure out what kind of Object the Node Buffer is, and how to translate that to Google Apps Script.
As written in node documentation,
Buffer objects are used to represent a fixed-length sequence of bytes. Many Node.js APIs support Buffers.
The Buffer class is a subclass of JavaScript's
Uint8Array
class and extends it with methods that cover additional use cases. Node.js APIs accept plain Uint8Arrays wherever Buffers are supported as well.
There is no direct support of Buffer
Apps script supports Byte Array
from Blob
s. So it is possible to emulate Buffer.from
At Google Apps script, Utilities.newBlob(str).getBytes()
returns Int8Array
. In order to convert unsigned hexadecimal array to the byte array for Google Apps Script, it is required to convert it to Int8Array
.
Apps script also directly supports Uint8Array
const Buffer={from: str => Utilities.newBlob(str).getBytes()};
var message_buffer = Buffer.from(message);
var signature_hash_from_buffer = Utilities.computeHmacSignature(Utilities.MacAlgorithm.HMAC_SHA_512, message_buffer , Buffer.from(secret));//modified as well