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();
}Report a problem with this exampleOpens a pre-filled issue on GitHub.