Skip to content

Instantly share code, notes, and snippets.

@tanaikech
Last active January 7, 2022 22:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tanaikech/9e9ab42ad225e127c59ae8ae598aacac to your computer and use it in GitHub Desktop.
Save tanaikech/9e9ab42ad225e127c59ae8ae598aacac to your computer and use it in GitHub Desktop.
About Updated Utilities.computeHmacSignature()

About Updated Utilities.computeHmacSignature()

By the Google's update at June 19, 2018, finally, Utilities.computeDigest(), Utilities.computeHmacSha256Signature() and Utilities.computeHmacSignature() got to be able to use the byte arrays. By this, using only native Google Apps Script, the result can be retrieved without using jsSHA. When I used the updated them, the response speed is much faster than that of jsSHA. It is considered that this may be optimized for Google Apps Script. As a sample, it shows 2 samples as follows. The both results are the same.

Sample script 1: Using jsSHA

var obj = new jsSHA("SHA-512", "TEXT");
obj.setHMACKey(key, "B64");
obj.update(value);
var res = obj.getHMAC("B64");

Sample script 2: Updated Utilities.computeHmacSignature()

var out = Utilities.computeHmacSignature(
    Utilities.MacAlgorithm.HMAC_SHA_512,
    Utilities.base64Decode(Utilities.base64Encode(value)),
    Utilities.base64Decode(key)
);
var res = Utilities.base64Encode(out);

Sample situation 1

c2FtcGxlS2V5 which converted "sampleKey" to base64 and sampleValue are used as the key and the value, respectively. Both sample scripts are as follows.

Sample script 1: Using jsSHA

var key = "c2FtcGxlS2V5";
var value = "sampleValue";
var obj = new jsSHA("SHA-512", "TEXT");
obj.setHMACKey(key, "B64");
obj.update(value);
var res = obj.getHMAC("B64");

Sample script 2: Updated Utilities.computeHmacSignature()

var key = "c2FtcGxlS2V5";
var value = "sampleValue";
var out = Utilities.computeHmacSignature(
    Utilities.MacAlgorithm.HMAC_SHA_512,
    Utilities.base64Decode(Utilities.base64Encode(value)),
    Utilities.base64Decode(key)
);
var res = Utilities.base64Encode(out);

The both results are BjnBG35lcpjmR6/001XiG/Cfassr8aGYheH31P3X0sJE8GyZ1hiNLl86QRDqpXxi640EW4Eedbn9LCh0OcvJHA==.

Sample situation 2

Also you can use the binary file as the key. The sample script is as follows.

var fileId = "###"; // binary file
var image = DriveApp.getFileById(fileId).getBlob().getBytes();
var key = Utilities.base64Encode(image);
var value = "sampleValue";
var out = Utilities.computeHmacSignature(
    Utilities.MacAlgorithm.HMAC_SHA_512,
    Utilities.base64Decode(Utilities.base64Encode(value)),
    Utilities.base64Decode(key)
);
var res = Utilities.base64Encode(out);

Sample situation 3

Stackoverflow: Google-App-Script vs php in encoding base64

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment