Browser Web Crypto API (crypto.subtle) & Key Management Reference
Essential reference for in-browser SHA-256 hashing, AES-GCM encryption, HMAC signing, and JWK key import/export.
Table of Contents
Cryptographic Hashing (SHA-256 / SHA-512)
Generating one-way cryptographic digests from strings and binary files.
| Algorithm | Code Snippet | Output Length |
|---|---|---|
| `SHA-256` | `await crypto.subtle.digest("SHA-256", dataBuffer)` | 32 bytes (64 hex characters) |
| `SHA-512` | `await crypto.subtle.digest("SHA-512", dataBuffer)` | 64 bytes (128 hex characters) |
| `Hex Conversion` | `Array.from(new Uint8Array(hash)).map(b => b.toString(16).padStart(2, "0")).join("")` | Formatted Hex String |
Symmetric Encryption (AES-GCM)
Authenticated encryption protecting both confidentiality and integrity.
| Operation | Algorithm Parameters | Code Example |
|---|---|---|
| Generate Key | `{ name: "AES-GCM", length: 256 }` | `await crypto.subtle.generateKey(alg, true, ["encrypt", "decrypt"])` |
| Random IV | `12 bytes (96-bit)` | `const iv = crypto.getRandomValues(new Uint8Array(12))` |
| Encrypt | `{ name: "AES-GCM", iv }` | `await crypto.subtle.encrypt(params, key, plaintextBuffer)` |
| Decrypt | `{ name: "AES-GCM", iv }` | `await crypto.subtle.decrypt(params, key, ciphertextBuffer)` |
Password-Based Key Derivation (PBKDF2)
Stretching user passwords into cryptographic AES keys resistant to brute-force attacks.
| Parameter | Recommended Production Setting | Security Purpose |
|---|---|---|
| `salt` | `crypto.getRandomValues(new Uint8Array(16))` | Prevents pre-computed Rainbow Table attacks |
| `iterations` | `600,000` (OWASP 2024 guidance) | Increases CPU cost for GPU password crackers |
| `hash` | `"SHA-256"` | Underlying pseudorandom function |
Interactive Client-Side Tools for this Guide
Test and run these patterns directly inside your browser with zero server uploads:
Online Hash Generator (MD5, SHA-256, SHA-512)
Compute message digests and cryptographic checksums using native Web Crypto API. 100% private and client-side.
Webhook HMAC Signature Generator & Verifier
Cryptographically sign and verify incoming webhook payloads with your secret key. Supports Stripe, GitHub, and Shopify standards with zero server uploads.
Protect & Encrypt PDF Online
Add tamper protection and security headers to confidential documents directly in your browser.
Frequently Asked Questions
Why is crypto.subtle only available in Secure Contexts (HTTPS)?
Browsers disable `window.crypto.subtle` on non-HTTPS origins (except localhost) to prevent man-in-the-middle attacks from tampering with cryptographic scripts or stealing plaintext keys.
Can crypto.getRandomValues be used for secure passwords and tokens?
Yes! `crypto.getRandomValues()` is cryptographically secure (CSPRNG), backed by the host operating system's entropy pool (e.g. `/dev/urandom` on Linux/macOS or `BCryptGenRandom` on Windows).