All articles

SHA-256 hashing in JavaScript with Web Crypto

· 2 min read

SHA-256 turns any input into a 256-bit fingerprint. The same input always produces the same hash, any change produces a completely different one, and you can't work backwards from the hash to the input. That makes it useful for integrity checks, cache keys, deduplication, signatures and content addressing. Modern JavaScript can compute it natively.

Hash a string

crypto.subtle.digest works on bytes and returns a promise for an ArrayBuffer. Encode the text as UTF-8, hash it, and convert the result to hex:

const toHex = (buffer) => Array.from(new Uint8Array(buffer), (b) => b.toString(16).padStart(2, "0")).join("");

async function sha256(text) {
  const bytes = new TextEncoder().encode(text);
  return toHex(await crypto.subtle.digest("SHA-256", bytes));
}

await sha256("hello");
// '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'

The same code runs in browsers, Node.js 19+ (where crypto is a global), Deno, Bun and edge runtimes. The supported algorithms are "SHA-1", "SHA-256", "SHA-384" and "SHA-512".

Hex or Base64

A SHA-256 digest is 32 bytes: 64 characters in hex, or 44 in Base64. Subresource Integrity and many APIs use Base64:

const base64 = btoa(String.fromCharCode(...new Uint8Array(digest)));

Hash a file

In the browser, read the file as an ArrayBuffer:

input.addEventListener("change", async () => {
  const file = input.files[0];
  const digest = await crypto.subtle.digest("SHA-256", await file.arrayBuffer());
  console.log(toHex(digest));
});

digest needs the whole file in memory. For very large files in the browser, a streaming library such as hash-wasm is a better fit. In Node.js, the classic crypto module streams:

import { createHash } from "node:crypto";
import { createReadStream } from "node:fs";

const hash = createHash("sha256");
for await (const chunk of createReadStream("video.mp4")) hash.update(chunk);
console.log(hash.digest("hex"));

For strings in Node.js, createHash("sha256").update(text).digest("hex") is synchronous and shorter.

Compare with the command line

printf 'hello' | shasum -a 256     # macOS
printf 'hello' | sha256sum         # Linux

Both print 2cf24dba...9824. With echo 'hello' you get 5891b5b5...6be03 instead, because echo adds a newline that becomes part of the input. This is the most common reason hashes don't match.

HMAC: hashing with a secret

A plain hash proves data wasn't changed only if the hash itself comes from a trusted place. To verify that a message came from someone who knows a secret (webhook signatures, signed URLs, HS256 JWTs), use HMAC:

async function hmacSha256(secret, message) {
  const enc = new TextEncoder();
  const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
  const signature = await crypto.subtle.sign("HMAC", key, enc.encode(message));
  return toHex(signature);
}

await hmacSha256("secret", "hello");
// '88aab3ede8d3adf94d26ab90d3bafd4a2083070c3bcce9c014ee04a443847c0b'

Don't build a MAC as sha256(secret + message): SHA-256 is vulnerable to length extension, so attackers can append data and compute a valid hash without the secret. HMAC is designed to prevent that.

When checking a received signature on a server, compare with a constant-time function (crypto.timingSafeEqual in Node.js) instead of ===. JWTs signed with HS256 are HMACs too, and verifying them involves more than the signature.

Don't hash passwords with SHA-256

SHA-256 is designed to be fast: a GPU can compute billions per second. That's great for checksums and terrible for passwords, because an attacker with a leaked database can test enormous numbers of guesses. Salting stops precomputed tables but not fast guessing.

Use an algorithm built to be slow and memory-hard, with a unique salt per password: Argon2id, scrypt or bcrypt (see the OWASP cheat sheet). In Node.js, crypto.scrypt is built in; Web Crypto offers PBKDF2, which is acceptable with a high iteration count.

Where SHA-256 fits

Use Algorithm
File integrity, checksums, cache keys SHA-256
Subresource Integrity (integrity="sha384-...") SHA-384 or SHA-256
Webhook and API signatures HMAC-SHA-256
Password storage Argon2id, scrypt, bcrypt
Random tokens and IDs crypto.getRandomValues, not a hash

If you need unpredictable values rather than fingerprints, generate them directly; generating secure passwords shows how.

Frequently asked questions

Why is crypto.subtle undefined?

Web Crypto's subtle API is only available in secure contexts: pages served over HTTPS or from localhost. Plain HTTP pages on other hosts don't get it.

Can SHA-256 be reversed?

No, but short or common inputs can be found by guessing: precomputed tables cover many passwords and short strings. That's why passwords need a slow, salted algorithm.

Is MD5 or SHA-1 still OK?

Not where an attacker could craft input: both have practical collision attacks. They're acceptable for non-security checksums. Web Crypto doesn't offer MD5 at all.

Why does my hash differ from the command line?

Usually a trailing newline (echo adds one; use printf or echo -n), a different text encoding, or comparing hex with Base64 output.

Further reading