Cryptographic Hashing in JavaScript (SHA-256)
Compute secure SHA-256 and SHA-512 cryptographic digests in modern JavaScript using the native Web Crypto API and Node.js crypto module.
Cryptographic hash functions transform arbitrary input data into a fixed-size, deterministic digest. In modern JavaScript applications, hashing is essential for verifying file checksums, generating API signatures, creating cache keys, and building distributed content identifiers.
Quick Start (Browser & Edge Runtimes)#
The standard Web Crypto API (crypto.subtle) is universally available across modern browsers, Cloudflare Workers, Deno, and Node.js 16+:
Quick Start (Node.js Backend)#
In Node.js backend services, the built-in node:crypto module provides synchronous and streaming hashing with high throughput:
Supported Algorithms#
The Web Crypto API supports the SHA-2 family:
"SHA-256": 256-bit digest (64 hex characters) — standard for security and verification."SHA-384": 384-bit digest (96 hex characters)."SHA-512": 512-bit digest (128 hex characters) — maximum collision resistance.
In Node.js crypto, MD5 and SHA-1 are also available for legacy compatibility and non-cryptographic checksums:
Hex vs Base64 Output#
Depending on your protocol requirements, you can format the output digest as hexadecimal or Base64:
Hashing Streams & Large Files in Node.js#
To hash gigabyte-scale files without exhausting system memory, stream the data through a hash transform stream:
Best Practices#
- Use SHA-256 as default: SHA-256 balances security and performance across all environments.
- Never use plain SHA for password storage: Always use specialized key derivation functions such as Argon2id, bcrypt, or PBKDF2 with salting and work factors.
- Handle UTF-8 encoding explicitly: In browsers, always use
TextEncoder()to ensure multi-byte Unicode strings hash identically across platforms.