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.
Code
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: trueHow 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
bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.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.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.