Google Apps Script - Convert cell to SHA256 within an Array Formula

809 views Asked by At

I have a simple script written to hash a cell, however it doesn't work within and array formula, and I am having a hard time figure out how to add that functionality.

function SHA256 (input) {
  var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, input);
  var txtHash = '';
  for (i = 0; i < rawHash.length; i++) {
    var hashVal = rawHash[i];
    if (hashVal < 0) {
      hashVal += 256;
    }
    if (hashVal.toString(16).length == 1) {
      txtHash += '0';
    }
    txtHash += hashVal.toString(16);
  }
  return txtHash;
}

Within Google Sheets, the above script allows me to hash using SHA526(A2)

I would like to be able to hash an entire column by using SHA256() within an array formula. =ArrayFormula(SHA256(A2:A))

The error I get is

"Exception: The parameters (DigestAlgorithm,number[]) don't match the method signature for Utilities.computeDigest. (line 2)."

Any direction would be greatly appreciated!

1

There are 1 answers

1
joshbjames On BEST ANSWER

Google Apps Script - Custom Functions Documentation

In order to use an array you need to map the input. Using a simple else if you can test if the input is an array or a single value.

function SHA256 (input) {
  if(input.map) {
    return input.map(SHA256);
  } else {
    var rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, input);
    var txtHash = '';
    for (i = 0; i < rawHash.length; i++) {
      var hashVal = rawHash[i];
      if (hashVal < 0) {
        hashVal += 256;
      }
      if (hashVal.toString(16).length == 1) {
        txtHash += '0';
      }
      txtHash += hashVal.toString(16);
    }
    return txtHash;
  }
}