Files and data

Hash a small byte buffer with Web Crypto

Use crypto.subtle.digest to compute a SHA-256 digest of a small byte buffer. The Web Crypto digest operation accepts bytes; encode text explicitly when text is the intended input.

Worked example

Node.js example · save as example.mjs and run node example.mjs

const bytes = new TextEncoder().encode("abc");
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
const hex = [...digest].map(byte => byte.toString(16).padStart(2, "0")).join("");
console.log(hex);

How it works

The digest is returned as an ArrayBuffer, then displayed in hexadecimal. Hashing the same bytes produces the same digest, making this useful for comparing a small file or fixture against a trusted reference.

Limits and mistakes

Browser Web Crypto availability depends on a secure context. Digest does not expose incremental hashing through this interface, so reading a huge file into one buffer can consume substantial memory. A digest is not a signature or proof of authorship.

Check the result

For abc expect ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad. Add a newline and confirm the digest changes because the input bytes changed.

Sources

Reference documentation for the behavior used in this guide: