![見出し画像](https://assets.st-note.com/production/uploads/images/119266380/rectangle_large_type_2_fec1ea9be22efa5fedf9d21882ba0c82.png?width=1200)
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に貼り付けると関数として使えます。
![](https://assets.st-note.com/img/1697637143657-bi4SjkbBLo.png?width=1200)
スプレッドシート上で使っているスクショです↓
![](https://assets.st-note.com/img/1697716112347-3x7yfkrFoo.png?width=1200)
※
アルファベットだと上手くハッシュ値が取れますが日本語文字だと文字コードの影響を受けるのか違う値が出ます。
「こんにちわバイデンです」のMD5ハッシュ値
GASだと
106D6A60386B448F80D401758C203F54
Windowsだと
ADD5F12E120F7E603259E6AAF452D859
![](https://assets.st-note.com/img/1697717525576-mw5B6fWcQG.png?width=1200)
![](https://assets.st-note.com/img/1697717541988-GknV5RBISt.png?width=1200)
同じUTF8なんですが、BOMアリかBOMナシかの違いでしょうか
#GoogleAppsScript #GAS #ハッシュ #GAS初心者 #初めてのGAS #Googleスプレッドシート