Cryptography & Web SecurityUpdated: 2026-11-06

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.

The Web Crypto API (`window.crypto.subtle`) is a standard, native browser interface providing hardware-accelerated cryptographic primitives. It enables client-side zero-knowledge document encryption, password hashing, and HMAC signature verification without external heavy JavaScript cryptography dependencies.

Cryptographic Hashing (SHA-256 / SHA-512)

Generating one-way cryptographic digests from strings and binary files.

AlgorithmCode SnippetOutput 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.

OperationAlgorithm ParametersCode 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.

ParameterRecommended Production SettingSecurity 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

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).