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.
Code
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 —
cryptowill 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
SHA-256 Hash GeneratorGenerate SHA-256 cryptographic hashes from text input using the Web Crypto API. Compare hashes and verify data integrity with hexadecimal digest output.HMAC GeneratorCompute an HMAC-SHA-256, SHA-384, or SHA-512 signature for a message and key using the Web Crypto API, with hex and Base64 output.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.JWT Signature InspectorInspect a JWT signature: decode the header and payload, show the algorithm and signature bytes, and verify HS256/384/512 HMAC signatures with a secret.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.