How to Generate a SHA-256 Hash in JavaScript
The Web Crypto API lets you compute SHA-256 hashes natively in both the browser and Node.js 18+. No npm install required.
Browser and modern Node.js (Web Crypto API)
async function sha256(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hashBuffer = await crypto.subtle.digest("SHA-256", data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
}
const hash = await sha256("hello");
console.log(hash);
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
crypto.subtle.digest returns an ArrayBuffer, so you convert it to a hex string manually. The TextEncoder handles Unicode correctly.
Node.js (built-in crypto module)
If you're on Node.js and prefer the older crypto module:
import { createHash } from "crypto";
function sha256(message) {
return createHash("sha256").update(message).digest("hex");
}
console.log(sha256("hello"));
// 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
This is synchronous and slightly simpler, but it's Node-only — it won't run in the browser.
Hashing a file
async function hashFile(file) {
const buffer = await file.arrayBuffer();
const hashBuffer = await crypto.subtle.digest("SHA-256", buffer);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
}
// Usage with a file input:
fileInput.addEventListener("change", async (e) => {
const hash = await hashFile(e.target.files[0]);
console.log(hash);
});
File hashing is useful for verifying that a download matches an expected checksum.
Other supported algorithms
crypto.subtle.digest also accepts "SHA-1", "SHA-384", and "SHA-512". MD5 is not supported by the Web Crypto API because it's considered insecure — see MD5 vs SHA-256 for why.
Try it without code
Paste any string into the hash generator to compute MD5, SHA-1, SHA-256, and SHA-512 instantly in your browser. Useful for quick checks or verifying your code produces the expected output.
For more on how hashing works under the hood, read what is a hash function.
Got a config file to check?
Open the config toolkit →