Skip to content

Instantly share code, notes, and snippets.

@mhawksey
Created April 26, 2019 18:37
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mhawksey/4876f901591fb7fd304a41923c2b4fcf to your computer and use it in GitHub Desktop.
Save mhawksey/4876f901591fb7fd304a41923c2b4fcf to your computer and use it in GitHub Desktop.
Example Google Apps Script custom sheet function example. For more info see https://mashe.hawksey.info?p=19219
/**
* Generates a SHA-256 hash of a text input.
*
* @param {String||Array} value to SHA-256 hash.
* @param {String} key to use to generate the hash with.
* @return the SHA-256 hash of the value
* @customfunction
*/
function HASH(value, key) {
if (typeof key !== 'string'){ // test the key is a string
throw "Key needs to be a text value";
}
if (value.map) { // Test whether input is an array.
return value.map(function(v){return HASH(v, key)}); // Recurse over array if so.
} else { // The bit that actual creates the hash
// based on https://stackoverflow.com/a/27933459
return Utilities.computeHmacSha256Signature(value, key).reduce(function(str, chr) {
chr = (chr < 0 ? chr + 256 : chr).toString(16);
return str + (chr.length == 1 ? '0' : '') + chr;
}, '');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment