Skip to content

Instantly share code, notes, and snippets.

@HaNdTriX
Last active April 10, 2024 08:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HaNdTriX/239f45939ee8b9f012861bb22808ba42 to your computer and use it in GitHub Desktop.
Save HaNdTriX/239f45939ee8b9f012861bb22808ba42 to your computer and use it in GitHub Desktop.
Convert a string to an sha256 hash in JavaScript
/**
* Convert a string to an sha256 hash
* @param str {string}
* @returns {string}
*/
async function sha256(str) {
const arrayBuffer = new TextEncoder("utf-8").encode(str)
const hashAsArrayBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer);
const uint8ViewOfHash = new Uint8Array(hashAsArrayBuffer);
return Array.from(uint8ViewOfHash).map((b) => b.toString(16).padStart(2, '0')).join('');
}
@HaNdTriX
Copy link
Author

HaNdTriX commented Sep 14, 2022

Test

(async () => {
  {
    const assertion = 'Will return the same hash for the same value'
    const hash1 = await sha256('foobar')
    const hash2 = await sha256('foobar')
    console.assert(hash1 === hash2, assertion)
  }
  {
    const assertion = 'Will return the different hashes for the different values'
    const hash1 = await sha256('foobar2')
    const hash2 = await sha256('foobar')
    console.assert(hash1 !== hash2, assertion)
  }
})()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment