Skip to content

Instantly share code, notes, and snippets.

@tariqk
Created February 10, 2018 13:03
Show Gist options
  • Save tariqk/2bd55495a76810de2ce87af3f6c5e4a3 to your computer and use it in GitHub Desktop.
Save tariqk/2bd55495a76810de2ce87af3f6c5e4a3 to your computer and use it in GitHub Desktop.
Hash digest functions for Google Sheets — uses Utilities.computeDigest() from Google App Scripts
/**
* Returns the hash digest of a single cell or an array of cells.
*
* @param {"Sample text"} input - Text to hash.
* @param {"MD5"} algorithm - (optional) Hashing algorithm to use. Choose between MD2, MD5, SHA-1, SHA-256, SHA-384 and SHA-512. Defaults to MD5.
* @customfunction
*/
function HASH(input, algorithm) {
input = input || "" // what, nothing? FINE, you get nothing. Jerks.
if (input.map) { // check if it's an array, and make sure that the same damn algorithm is used.
return input.map(
function(input) {
return singular_hash_(input, algorithm);} );
}
else {
return singular_hash_(input, algorithm)
}
}
/**
* Private helper function for HASH(). Only deals with single strings.
*
* @param {string} input - Text to hash.
* @param {string} [opt_algo] - optional algorithm. Can only really use the algorithms provided by Utilities.DigestAlgorithm
* @returns {string} a base64-encoded, web-safe hash.
*/
function singular_hash_(input, opt_algo) {
var algorithm_to_use = { "md2": Utilities.DigestAlgorithm.MD2,
"md5": Utilities.DigestAlgorithm.MD5,
"sha1": Utilities.DigestAlgorithm.SHA_1,
"sha256": Utilities.DigestAlgorithm.SHA_256,
"sha384": Utilities.DigestAlgorithm.SHA_384,
"sha512": Utilities.DigestAlgorithm.SHA_512 };
old_opt_algo = opt_algo // in case shit goes wrong
opt_algo = opt_algo || "md5" // default to MD5 if no algorithm specified
opt_algo = opt_algo.replace(/[^a-z0-9]+/i, "").toLowerCase(); //strip out anything that aren't letters and numbers, and smash everything to lower case.
if(algorithm_to_use[opt_algo] == undefined) {
throw new Error("Unknown hashing algorithm (What's " + old_opt_algo + "?"); // good thing we saved the original text before we mangled it half to death.
}
else {
return Utilities.base64EncodeWebSafe(Utilities.computeDigest(algorithm_to_use[opt_algo], input));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment