Public
Script
Readme

Creating a SHA-256 hash of a string

This example shows how you can hash a string using SHA-256 without using any NPM modules – just web standards! Adapted from an example on MDN.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export let sha256Example = (async () => {
const message = "Hello world";
// encode as (utf-8) Uint8Array
const msgUint8 = new TextEncoder().encode(message);
// hash the message
const hashBuffer = await crypto.subtle.digest("SHA-256", msgUint8);
// convert buffer to byte array
const hashArray = Array.from(new Uint8Array(hashBuffer));
// convert bytes to hex string
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join("");
return hashHex;
})();
Val Town is a social website to write and deploy JavaScript.
Build APIs and schedule functions from your browser.
Comments
Nobody has commented on this val yet: be the first!
October 23, 2023