If you use Github (or bit torrent sites), you’ll notice that there is sometimes a code called a sha used to reference files. This is actually a hash of the contents of the file. If you change the contents then the hash changes, so its a good way to know if there’s been any updates or indeed if two files are the same as each other.

It’s also used to enable a concept known as ‘content addressable files’. GitHub is based on this, and files can be found by their hash. It is fairly straightforward to create a sha out of any content using apps script.

The sha for

here is some content

is

65e31cd4574788f870e5a17bcbb611a9f4cc4593

You’ll find these snippets in the cUseful library, or you can see the code below.

so to create the sha above, you would use

cUseful.makeSha1Hex ("here is some content");

The code

/**
* make a hex sha1 string
* @param {string} content some content
* @return {string} the hex result
*/
function makeSha1Hex (content) {
  return byteToHexString(Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_1, content));
}
/**
* convert an array of bytes to a hex string
* @param {Array.byte} bytes the byte array to convert
* @return {string} the hex encoded string
*/
function byteToHexString (bytes) {
  return bytes.reduce(function (p,c) {
    return p += padLeading ((c < 0 ? c+256 : c).toString(16), 2 );
  },'');
}
/**
* pad leading part of string
* @param {string} stringtoPad the source string
* @param {number} targetLength what the final string length should be
* @param {string} padWith optional what to pad with - default "0"
* @return {string} the padded string
*/
function padLeading (stringtoPad , targetLength , padWith) {
  return (stringtoPad.length < targetLength ? Array(1+targetLength-stringtoPad.length).join(padWith | "0") : "" ) + stringtoPad ;
}
/**
* get base64 encoded data as a string
* @param {string} b64 as a string
* @return {string} decoded as as string
*/
function b64ToString ( b64) {
  return Utilities.newBlob(Utilities.base64Decode(result.content)).getDataAsString();
  }

The cUseful library

Many of the snippets in this section of the site are part of the cUseful library. You can find the details below.

And that’s all there is to it. Happy hashing

For more like this see Google Apps Scripts Snippets
Why not join our forum,follow the blog or follow me on twitter to ensure you get updates when they are available.