Skip to content

Instantly share code, notes, and snippets.

@mogsdad
Last active October 29, 2021 03:28
Show Gist options
  • Save mogsdad/5464686 to your computer and use it in GitHub Desktop.
Save mogsdad/5464686 to your computer and use it in GitHub Desktop.
This Google Apps Script function returns a string representing the 16-byte MD5 digest of a given message. It was originally written as an answer to StackOverflow question http://stackoverflow.com/questions/16216868/get-back-a-string-representation-from-computedigestalgorithm-value-byte. It's been refactored to support adaptation to other digest …
/**
* Return string representation of MD5 digest of the given message.
*
* @param {String} message Message to be encoded.
*
* @return {String} 16-byte digest value
*/
function signMd5(message){
return digest(Utilities.DigestAlgorithm.MD5, message);
}
/**
* Return string representation of SHA_256 digest of the given message.
*
* @param {String} message Message to be encoded.
*
* @return {String} 16-byte digest value
*/
function signSHA_256(message){
return digest(Utilities.DigestAlgorithm.SHA_256, message);
}
/**
* Return string representation of digest of the given string,
* using the indicated digest algorithm.
*
* @see {link https://developers.google.com/apps-script/reference/utilities/digest-algorithm|
* Enum DigestAlgorithm}
*
* @param {DigestAlgorithm}
* @param {String} message Message to be encoded.
*
* @return {String} 16-byte digest value
*/
function digest(algorithm,aStr) {
algorithm = algorithm || Utilities.DigestAlgorithm.MD5; // default MD5
aStr = aStr || ""; // default to empty string
var signature = Utilities.computeDigest(algorithm, aStr,
Utilities.Charset.US_ASCII)
//Logger.log(signature);
var signatureStr = '';
for (i = 0; i < signature.length; i++) {
var byte = signature[i];
if (byte < 0)
byte += 256;
var byteStr = byte.toString(16);
// Ensure we have 2 chars in our byte, pad with 0
if (byteStr.length == 1) byteStr = '0'+byteStr;
signatureStr += byteStr;
}
//Logger.log(signatureStr);
return signatureStr;
}
@radzak
Copy link

radzak commented Apr 27, 2020

Note that Google Apps Script also supports Utilities.Charset.UTF_8 as a Charset representing the input character set. Any benefit of not using it as a default nowadays?

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