Codectionary / Developer documentation / JavaScript

Computing a SHA-256 Digest

crypto.subtle.digest computes a digest of supplied bytes and returns an ArrayBuffer asynchronously. SHA-256 is useful for content fingerprints and integrity workflows, but an unauthenticated hash does not prove who produced the content. Web Crypto subtle APIs require a secure browser context.

Syntax

await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));

Examples

Computing a SHA-256 Digest: working example

Run this standalone example in a modern browser console unless another environment is specified. Expected result: On HTTPS or localhost, the console prints ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.

(async () => {
  const input = new TextEncoder().encode("abc");
  const digest = await crypto.subtle.digest("SHA-256", input);
  const hex = Array.from(new Uint8Array(digest), b => b.toString(16).padStart(2, "0")).join("");
  console.log(hex);
})();
  1. Expected result: On HTTPS or localhost, the console prints ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad.
  2. Text is explicitly encoded as UTF-8 before hashing.
  3. The 32-byte digest is rendered as 64 hexadecimal characters.

Best practices

  • Do not use a fast general-purpose digest alone for password storage.
  • Use authenticated mechanisms when adversaries could replace both content and its expected digest.

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

Specifications & further reading