見出し画像

GASで文字列のハッシュ値を求めたい


Google Apps Script (GAS)でハッシュ値を求めるときの備忘録です


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

function HashMD5 (input='') {
 if(input==''){return "";}
 const rawHash = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, input);
 let txtHash = '';
 for (let i = 0; i < rawHash.length; i++) {
  let hashVal = rawHash[i];
  if (hashVal < 0) {
   hashVal += 256;
  }
  if (hashVal.toString(16).length == 1) {
   txtHash += '0';
  }
  txtHash += hashVal.toString(16);
 }
 return txtHash.toUpperCase();
}


上のプログラムをAppsScriptに貼り付けると関数として使えます。

スプレッドシート上で使っているスクショです↓



アルファベットだと上手くハッシュ値が取れますが日本語文字だと文字コードの影響を受けるのか違う値が出ます。
「こんにちわバイデンです」のMD5ハッシュ値

GASだと
 106D6A60386B448F80D401758C203F54
Windowsだと
 ADD5F12E120F7E603259E6AAF452D859


同じUTF8なんですが、BOMアリかBOMナシかの違いでしょうか




#GoogleAppsScript #GAS #ハッシュ #GAS初心者 #初めてのGAS #Googleスプレッドシート


この記事が気に入ったらサポートをしてみませんか?