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
MethodAlgorithm OptionsPurpose / Action
crypto.subtle.digest()SHA-256, SHA-384, SHA-512Calculate cryptographic hash digest
crypto.subtle.generateKey()AES-GCM, HMAC, RSA-OAEPGenerate symmetric or asymmetric keypair
crypto.subtle.encrypt()AES-GCM (needs 12-byte IV)Encrypt plaintext ArrayBuffer
crypto.subtle.decrypt()AES-GCMDecrypt 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:// or localhost). Accessing window.crypto.subtle over plain http:// in production will return undefined!

[!TIP] Always generate a unique 12-byte iv (Initialization Vector) via crypto.getRandomValues() for every AES-GCM encryption operation.