Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 1 min read

SHA-256 in the browser with Web Crypto (and why MD5 isn't there)

You don't need a library to hash a string in the browser. The Web Crypto API has had crypto.subtle.digest in every modern browser for years: async function sha256(text) { const data = new TextEncoder().encode(text);

You don't need a library to hash a string in the browser. The Web Crypto API has had crypto.subtle.digest in every modern browser for years:

async function sha256(text) {
  const data = new TextEncoder().encode(text);
  const buf = await crypto.subtle.digest("SHA-256", data);
  return [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, "0")).join("");
}
await sha256("hello"); // "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824"

A few things that trip people up:

1. It's async. digest returns a Promise of an ArrayBuffer, not a string. You convert to hex yourself.

2. Encoding matters. TextEncoder gives UTF-8. If your server hashes UTF-16 or Latin-1, the digests won't match even for the same visible text. Trailing newlines and spaces count too.

3. Secure contexts only. crypto.subtle is only available on HTTPS (and localhost). On a plain http:// page it's undefined.

4. The supported list is short: SHA-1, SHA-256, SHA-384 and SHA-512. No MD5. That's deliberate: MD5 is broken for anything security-related. If you need it for a legacy checksum, you'll need a small library.

5. Hashing isn't password storage. A fast hash like SHA-256 is the wrong tool for passwords. Use a slow, salted algorithm (bcrypt, scrypt, Argon2, or PBKDF2 via crypto.subtle.deriveBits) on the server.

Good uses for a plain digest: cache keys, comparing two blobs of text, content IDs, and checking test output against a known value.

Disclosure: I run GoToolsOnline. Its free hash generator does SHA-256/384/512 with Web Crypto and MD5 with a small library, all on your device, handy for quickly checking a value: https://gotoolsonline.com/tools/hash-generator

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.