About Updated Utilities.computeHmacSignature()

Gists

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

 Share!