LoginSignup
43
35

More than 3 years have passed since last update.

JavaScriptで文字列のハッシュ値を取得する

Last updated at Posted at 2020-03-02

JavaScriptで文字列をハッシュ化する方法を探していた。
ライブラリを使わず、ブラウザだけでできないかなーと。

ようやく見つけたので記録に。

ソースコード
async function sha256(text){
    const uint8  = new TextEncoder().encode(text)
    const digest = await crypto.subtle.digest('SHA-256', uint8)
    return Array.from(new Uint8Array(digest)).map(v => v.toString(16).padStart(2,'0')).join('')
}
使い方
sha256('あいうえお').then(hash => console.log(hash))
// fdb481ea956fdb654afcc327cff9b626966b2abdabc3f3e6dbcb1667a888ed9a

参考: https://developer.mozilla.org/ja/docs/Web/API/SubtleCrypto/digest

43
35
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
43
35