SHA256 Hash
by bryandowning
HTML
see browser console
JavaScript
/**
* Cobbled together from:
* https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API/Non-cryptographic_uses_of_subtle_crypto
* and
* https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest
*/
const text = "[email protected]";
// example hash result: d06b30ffd7be5d9898ae79360fc09e3ddd3bf71366de63facbb025b1b0245426
async function hash(message) {
// Encode as (utf-8) Uint8Array
const data = new TextEncoder().encode(message.toLowerCase());
// Hash the text
const hash = await crypto.subtle.digest("SHA-256", data);
// To display it as a string we will get the hexadecimal value of
// each byte of the array buffer. This gets us an array where each byte
// of the array buffer becomes one item in the array
const uint8ViewOfHash = new Uint8Array(hash);
// We then convert it to a regular array so we can convert each item
// to hexadecimal strings, where characters of 0-9 or a-f represent
// a number between 0 and 15, containing 4 bits of information,
// so 2 of them is 8 bits (1 byte).
const hashAsString = Array.from(uint8ViewOfHash)
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return hashAsString;
}
// Execute
hash(text).then((result) => console.log(result));