What is a Cryptographic Hash?
A cryptographic hash function is a mathematical algorithm that maps data of an arbitrary size (like a password or a massive 10GB file) to a bit string of a fixed size. The output is commonly called the hash value, hash code, or simply the digest.
Unlike encryption, hashing is a one-way function. You cannot "decrypt" a SHA-256 hash to reveal the original input. This makes hashing perfect for verifying data integrity, storing passwords securely (when combined with a salt via PBKDF2), and generating unique digital signatures.
Why use the Web Crypto API for hashing?
Historically, developers had to import heavy, external JavaScript libraries like crypto-js to generate hashes in the browser. Today, modern browsers provide the window.crypto.subtle.digest() method natively. Using the native Web Crypto API provides massive benefits:
- Performance: Native C++ browser implementations are vastly faster than JS polyfills.
- Security: Eliminates the risk of third-party NPM package supply-chain attacks.
- Privacy: Data never leaves the client's device, ensuring compliance with strict privacy architectures.
How to generate a SHA-256 hash in JavaScript
If you want to implement hashing in your own application, here is the clean, zero-dependency approach using vanilla JavaScript and the SubtleCrypto interface:
async function generateHash(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
// Generate the raw ArrayBuffer digest
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
// Convert the buffer to a Hex string for readability
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}