# Web Crypto API and SubtleCrypto vs DOM XSS Prevention with Trusted Types

- **Canonical URL:** https://frontend.rocks/vs/web-crypto-subtle-vs-dom-xss-trusted-types/
- **Relation:** Contrasts With
- **Last Verified:** 2026-11-15
- **Verdict:** Non-extractable CryptoKeys resist exfiltration even if an XSS payload executes in the page.

## Comparison Matrix

| Dimension | Web Crypto API and SubtleCrypto | DOM XSS Prevention with Trusted Types |
| :--- | :--- | :--- |
| **Maturity** | Baseline · Widely | Experimental |
| **Domain** | Web APIs | Security & Accessibility |
| **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. |
| **Prerequisites** | Event Loop, Macrotasks, and Microtask Queue (SubtleCrypto returns Promises that resolve on the microtask queue after native thread work.) | Browser Rendering Pipeline (Critical Rendering Path) (DOM sinks invoke the HTML parser and script execution pipeline directly from JavaScript.) |
| **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. |

## Web Crypto API and SubtleCrypto — Under the Hood
`SubtleCrypto` is a bank safe-deposit box with a slot in the door: you slide plaintext in, and ciphertext slides out, while the key inside can be marked `extractable: false` so even an [XSS](/concepts/dom-xss-trusted-types) script cannot read the raw key bytes.

1. **Native Offload**: Calls dispatch to an internal browser crypto thread pool, resolving Promises on the [Event Loop](/concepts/event-loop-tasks-microtasks) without blocking frames.
2. **Non-Extractable Keys**: Keys generated or imported with `extractable: false` can be stored in [IndexedDB](/concepts/indexeddb-transactions-quotas) and used to sign or decrypt, yet `exportKey()` rejects.
3. **Hardware Acceleration**: Engines route AES-GCM and SHA-256 to CPU AES-NI / ARMv8 crypto instructions.

```js
const key = await crypto.subtle.generateKey(
  { name: 'AES-GCM', length: 256 },
  false, // non-extractable: JS can never read raw key bytes
  ['encrypt', 'decrypt']
);
const iv = crypto.getRandomValues(new Uint8Array(12));
const ciphertext = await crypto.subtle.encrypt(
  { name: 'AES-GCM', iv },
  key,
  new TextEncoder().encode('sensitive-payload')
);
```

## DOM XSS Prevention with Trusted Types — Under the Hood
Trusted Types acts like a factory safety interlock on a hydraulic press: the machine refuses to cycle unless the material carries a stamped inspection tag (`TrustedHTML`) from an approved quality gate (`trusted-types` CSP allowlist).

1. **Sink Lockdown**: Adding `require-trusted-types-for 'script'` to [Content Security Policy](/concepts/csp-nonces-strict-dynamic) instructs the DOM bindings to reject plain `string` arguments at every injection sink.
2. **Named Policies**: `trustedTypes.createPolicy('app-html', { createHTML })` centralizes sanitization (such as DOMPurify) into one auditable call site.
3. **Parser Isolation**: Even if an attacker controls URL parameters or `postMessage` data, the [Browser Rendering Pipeline](/concepts/browser-rendering-pipeline) never parses raw markup unless it passes through a policy.

```js
// Requires CSP: require-trusted-types-for 'script'; trusted-types app-sanitizer;
const sanitizer = trustedTypes.createPolicy('app-sanitizer', {
  createHTML: (input) => DOMPurify.sanitize(input),
});

container.innerHTML = sanitizer.createHTML(userBio);
// container.innerHTML = userBio; -> throws TypeError!
```

## Interactive Labs & Dissections
- [Web Crypto API and SubtleCrypto Lab](https://frontend.rocks/concepts/web-crypto-subtle/#lab) ([Markdown](https://frontend.rocks/concepts/web-crypto-subtle.md))
- [DOM XSS Prevention with Trusted Types Lab](https://frontend.rocks/concepts/dom-xss-trusted-types/#lab) ([Markdown](https://frontend.rocks/concepts/dom-xss-trusted-types.md))

## Related Architecture Autopsies
- [Autopsy #11: Anatomy of a Supply-Chain DOM XSS & How Trusted Types Stop It](https://frontend.rocks/autopsies/third-party-script-xss-takeover/) ([Markdown](https://frontend.rocks/autopsies/third-party-script-xss-takeover.md)): Compromised third-party widget injects an inline script via an innerHTML sink and exfiltrates session tokens.

## Primary Sources
- https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto
- https://w3c.github.io/webcrypto/
- https://developer.mozilla.org/en-US/docs/Web/API/Trusted_Types_API
- https://w3c.github.io/trusted-types/dist/spec/
