Web Crypto API Cheat Sheet
Quick reference guide for Web Crypto API: SubtleCrypto hashing, HMAC, key generation, encryption, and JWK export.
Security Tools
webcrypto
crypto
subtlecrypto
The Web Crypto API provides a standard set of low-level cryptographic primitives (window.crypto.subtle) directly in modern browsers and Node.js.
Hash Digest (SHA-256) Example
typescript
async function sha256(message: string): Promise<string> {
const encoder = new TextEncoder();
const data = encoder.encode(message);
// Compute SHA-256 buffer
const hashBuffer = await window.crypto.subtle.digest("SHA-256", data);
// Convert ArrayBuffer to Hex string
const hashArray = Array.from(new Uint8Array(hashBuffer));
return hashArray.map(b => b.toString(16).padStart(2, "0")).join("");
}
SubtleCrypto Core Operations
Table
| Method | Algorithm Options | Purpose / Action |
|---|---|---|
crypto.subtle.digest() | SHA-256, SHA-384, SHA-512 | Calculate cryptographic hash digest |
crypto.subtle.generateKey() | AES-GCM, HMAC, RSA-OAEP | Generate symmetric or asymmetric keypair |
crypto.subtle.encrypt() | AES-GCM (needs 12-byte IV) | Encrypt plaintext ArrayBuffer |
crypto.subtle.decrypt() | AES-GCM | Decrypt ciphertext ArrayBuffer |
crypto.subtle.exportKey() | "jwk", "spki", "pkcs8" | Export key to JWK or DER-encoded ArrayBuffer; add base64 encoding and PEM headers separately for PEM output |
AES-GCM Encryption & Decryption
typescript
async function encryptAES(text: string, secretKey: CryptoKey) {
const iv = window.crypto.getRandomValues(new Uint8Array(12)); // 96-bit IV
const encodedText = new TextEncoder().encode(text);
const ciphertext = await window.crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
secretKey,
encodedText
);
return { ciphertext, iv };
}
Common Pitfalls & Tips
[!WARNING] Web Crypto API operations are only available in Secure Contexts (
https://orlocalhost). Accessingwindow.crypto.subtleover plainhttp://in production will returnundefined!
[!TIP] Always generate a unique 12-byte
iv(Initialization Vector) viacrypto.getRandomValues()for every AES-GCM encryption operation.