SHA-256 Digest of Text With Web Crypto

Hash strings or byte arrays with SHA-256 through Web Crypto and return lowercase hexadecimal suitable for integrity checks.

TypescriptSecurity Boundaries

Code

typescriptsnippet
16 lines
export async function sha256Hex(input: string | Uint8Array): Promise<string> {
  if (typeof input !== "string" && !(input instanceof Uint8Array)) {
    throw new TypeError("input must be a string or Uint8Array");
  }
  const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
  const digest = await crypto.subtle.digest("SHA-256", bytes);
  return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
}

export async function verifySha256(input: string | Uint8Array, expectedHex: string): Promise<boolean> {
  if (typeof expectedHex !== "string" || !/^[0-9a-f]{64}$/i.test(expectedHex)) {
    throw new RangeError("expectedHex must contain 64 hexadecimal characters");
  }
  const actual = await sha256Hex(input);
  return actual === expectedHex.toLowerCase();
}

How the snippet works

The moving parts are the functions sha256Hex and verifySha256.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. Invalid states are rejected up front: it throws TypeError and RangeError instead of continuing with bad data.

What to watch for

  • This is browser-side code — crypto will not resolve in Node.

Applying it

The main signature reads export async function sha256Hex(input: string | Uint8Array)

sha256Hex is the public entry point; everything else in the file exists to support it.

Statements that matter

return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("");
throw new RangeError("expectedHex must contain 64 hexadecimal characters");
throw new TypeError("input must be a string or Uint8Array");

Interactive Tools for This Topic

FAQ

Is there a failure path for bad input?
The code refuses to continue: `TypeError` and `RangeError` is thrown while the state is still recoverable.
Does it depend on any third-party library?
No third-party library is referenced; the standard library covers it. The file defines `sha256Hex`, `verifySha256` at load time.