crypto.subtle.digest Hashes Text Bytes

Hash UTF-8 text with crypto.subtle.digest, convert the digest to hex, compare repeated and case-changed inputs, and check the fixed length.

JavascriptSecurity Boundaries

Code

javascriptsnippet
21 lines
async function sha256Hex(text) {
  const bytes = new TextEncoder().encode(text);
  const digest = await crypto.subtle.digest("SHA-256", bytes);
  return Array.from(
    new Uint8Array(digest),
    (byte) => byte.toString(16).padStart(2, "0"),
  ).join("");
}

async function main() {
  const first = await sha256Hex("devexamples");
  const second = await sha256Hex("devexamples");
  const other = await sha256Hex("Devexamples");

  console.log("digest:", first);
  console.log("hex length:", first.length);
  console.log("stable:", first === second);
  console.log("case sensitive:", first !== other);
}

main();

Output

Captured from a sandboxed run of this snippet in the build pipeline.

digest: 7e46fa4fad62b3c976e5192e3f1f96e9375ccc3f28a883d3c4c8d462dbeaa72e
hex length: 64
stable: true
case sensitive: true

How it works

crypto.subtle.digest Hashes Text Bytes comes down to the functions sha256Hex and main.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • Uses crypto, so it needs a browser context — it will not run as-is in Node without shims.

Using it

Signature: async function sha256Hex(text)

Running the file prints labeled results such as digest:, hex length:, stable: — each operation’s effect is visible in the output.

Running the file executes main, which drives sha256Hex in order.

Key statements

const digest = await crypto.subtle.digest("SHA-256", bytes);
const second = await sha256Hex("devexamples");
const first = await sha256Hex("devexamples");

Interactive Tools for This Topic

FAQ

What does crypto.subtle.digest Hashes Text Bytes print when run?
No setup needed: run the file and look for labeled lines like `digest:`, `hex length:`, `stable:` in the output.