技術メモ(主に自分向け)

短期記憶の自分向けの技術メモです。

ハッシュ値と暗号化の書き方

Apexクラスでハッシュ値の作成と暗号化の書き方をメモ。
(もしかしたら他に良い書き方があるかもですが、、、参考程度に)

Integer intToken = 99; //tokenの文字列を100文字と設定
Integer position;
String charList = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; //ハッシュ値に使用する文字列
String strHash = '';

//ハッシュ値作成
for (Integer i = 0; i <= intToken; i++) {
 position = Integer.valueof(String.valueof(Math.roundToLong(charList.length() * Math.random))) - 1;
 if (position < 0) position = 0;
 strHash += charList.substring(position, poosition + 1);
}

//暗号化
if (!String.isBlank(strHash)) {
 EncodingUtil.convertToHex(Crypto.generateDigest('H-256', Blob.valueOf(strHash))):
}

EncodingUtil.base64Encode(hash)の場合、桁落ちする可能性があるため
EncodingUtil.convertToHexをかませて16新文字列にしています。