Web Crypto API and SubtleCrypto vs DOM XSS Prevention with Trusted Types
Non-extractable CryptoKeys resist exfiltration even if an XSS payload executes in the page.
Structured Comparison Matrix
| Dimension | Web Crypto API and SubtleCrypto | DOM XSS Prevention with Trusted Types |
|---|---|---|
| Mental Model | Native C++-backed cryptographic primitives (AES-GCM, SHA-256, ECDSA, HKDF) running off the JS thread in secure contexts with non-extractable CryptoKey handles. | Type-enforced browser defense that locks dangerous DOM sinks (innerHTML, eval, script.src) against raw strings, permitting only objects minted by audited TrustedTypePolicy sanitizers. |
| Maturity & Domain | Baseline · Widely · Web APIs Chrome 37+ · Firefox 34+ · Safari 11+ | Experimental · Security & Accessibility Chrome 83+ · Firefox 135+ (partial / rolling out) · Safari 26+ (rolling out) |
| Prerequisites | ||
| When Not to Use | When not to use SubtleCrypto: Never roll custom client-side password hashing to replace server-side Argon2id or TLS transport security. | When not to use innerHTML at all: For plain text or structured UI updates, assign element.textContent or render framework JSX nodes, they never invoke the HTML parser and need zero policies. |
Engine Mechanics & Trade-Offs
SubtleCrypto dispatches cryptographic operations off the JS thread to the browser's native C++ crypto library and isolates raw key bytes behind opaque CryptoKey handles.
Key Pitfalls: Reusing an AES-GCM IV: Encrypting two messages with the same key and 12-byte iv destroys confidentiality and authentication; always call crypto.getRandomValues(new Uint8Array(12)) per message. Missing window.isSecureContext: crypto.subtle is undefined on plain http:// staging URLs; test over HTTPS or localhost.
The DOM parser and script loader reject plain strings at ~60 dangerous sinks unless wrapped by an audited TrustedTypePolicy.
Key Pitfalls: Registering a pass-through default policy: Writing createHTML: (s) => s silences errors while keeping every XSS vulnerability wide open. Enabling enforcement without Report-Only rollout: Turning on require-trusted-types-for 'script' immediately breaks third-party scripts that assign strings to innerHTML; audit with Con