← Guides

Developer Guide

Hash Generation in JavaScript

Working examples for SHA-256 and MD5 in the browser (Web Crypto) and Node.js crypto. Includes hex encoding and when not to use MD5.

javascript hashsha256 javascriptcrypto js hashweb crypto apinodejs crypto hash

JavaScript can hash strings and files in the browser with the Web Crypto API, and on the server with the Node.js crypto module. Use SHA-256 for integrity and fingerprints. Do not use MD5 or SHA-1 for security. This page shows copy-paste patterns and how to turn an ArrayBuffer into a hex string.

Browser: SHA-256 with Web Crypto

crypto.subtle.digest is async and available on https pages and localhost. Encode the string with TextEncoder, digest it as SHA-256, then map the Uint8Array to hex. Example: const data = new TextEncoder().encode(text); const buf = await crypto.subtle.digest("SHA-256", data); const hex = [...new Uint8Array(buf)].map(b => b.toString(16).padStart(2, "0")).join(""); Web Crypto does not expose MD5. For a quick MD5 or SHA-1 check, use a client-side tool or a library — never for passwords.

Node.js: crypto.createHash

Node is simpler and can be sync: crypto.createHash("sha256").update(data, "utf8").digest("hex"). You can stream large files with hash.update(chunk) and hash.digest("hex") at the end. SHA-256, SHA-384, and SHA-512 are available. MD5 still exists for legacy checksums; do not use it to store passwords or sign tokens.

Hex vs Base64 output

Hex is the usual display format (64 characters for SHA-256). Base64 is shorter and useful in headers or JSON. In the browser, convert the digest ArrayBuffer with btoa(String.fromCharCode(...new Uint8Array(buf))) or, better, Buffer in Node: digest("base64"). Do not confuse hashing with encryption — a hash cannot be reversed into the original input.

Which algorithm to pick

SHA-256 is the default for file integrity, git-like fingerprints, and cache keys. SHA-512 is finer-grained but longer. MD5 and SHA-1 are broken for collision resistance; they are acceptable only when you must match a legacy checksum. Password storage needs a slow, salted KDF (bcrypt, scrypt, Argon2) — not a single SHA-256 of the password.

Common mistakes

Hashing in the browser does not hide the input from the user or from XSS. Subtle.digest is not available in insecure HTTP contexts outside localhost. Comparing hex strings must be timing-safe on the server when the hash is a secret. And hashing a JSON object requires a stable key order — JSON.stringify is not stable across runtimes unless you sort keys yourself.

Summary

Use Web Crypto or Node crypto for SHA-256, encode the digest as hex, and reserve MD5 for legacy checksums. To compare outputs quickly, paste the same string into the Hash Generator and check SHA-256 next to MD5.

Try it yourself

Put what you've learned into practice with our free browser-native tool.

Open Tool →