SHA-256 Hashing Explained: Web Crypto API Examples
What is a hash? Where SHA-256 is used, and how to implement it in-browser using the Web Crypto API.
SHA-256 Hashing Explained
What is a Hash Function?
A hash function takes arbitrary input and produces a fixed-length output (digest). SHA-256 produces 256 bits (64 hex characters).
Key Properties
- One-way: Cannot reconstruct input from the hash
- Collision resistance: Extremely unlikely for two different inputs to produce the same hash
- Deterministic: Same input always produces the same hash
Use Cases
- Password storage: Store hash (+ salt), never plaintext
- File integrity: Verify downloaded files haven't been tampered with
- Digital signatures: Generate message digest for signing
- Cache keys: Unique content identifiers
Web Crypto API Implementation
async function sha256(text) {
const encoder = new TextEncoder();
const data = encoder.encode(text);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
}
const hash = await sha256('Hello, World!');
// dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986d
Summary
SHA-256 can be computed entirely in-browser using the native Web Crypto API — no libraries required and no data leaves the device.