Things I want to do
This code retrieves the value of a hash (‘SHA-256’) using JavaScript.
implementation
You can obtain the hash using the following function.
async function digestMessage(message) {
const msgUint8 = new TextEncoder().encode(message); // (utf-8 の) Uint8Array にエンコード
const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8); // メッセージのハッシュ値を取得
const hashArray = Array.from(new Uint8Array(hashBuffer)); // バッファーをバイト列に変換
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, "0")).join(""); // バイト列を 16 進文字列に変換
return hashHex;
}The caller should look like this: (Since it’s an async function, you need to receive the return value using either await or Then.)
const str ="ハッシュを求める文字列";
const hash = await digestMessage(str);Besides ‘SHA-256’ in crypto.subtle.digest'SHA-1' 'SHA-384' 'SHA-512'You can specify this.
'SHA-1'This is prohibited for use in encryption.
Result
I was able to obtain the hash value using JavaScript.
'e5f8d3681f38da0737857b4b0136362fdd62f3558274a54cb07c32f63143d203'Websites I used as references
SubtleCrypto: digest() メソッド - Web API | MDN
digest() は SubtleCrypto インターフェイスのメソッドで、指定されたデータのダイジェストを返します。ダイジェストとは、可変長の入力に由来する固定長の短い値です。暗号的ダイジェスト値は耐衝突性を示すため、同じダイジェスト値を持つ 2 つの異なる入力を見つけるのは非常に困難です。


コメント