WebCrypto generateKey And JWK exportKey Roundtrip
Persist WebCrypto keys as JWK: generateKey an extractable AES-GCM key, exportKey its JWK, then importKey it back and verify the material matches.
Code
// WebCrypto key lifecycle: generate an extractable key, persist it as JWK,
// and rebuild it later without holding raw key bytes in application state.
const key = await crypto.subtle.generateKey(
{ name: 'AES-GCM', length: 256 },
true, // extractable: required for exportKey
['encrypt', 'decrypt'],
);
const jwk = await crypto.subtle.exportKey('jwk', key);
console.log('kty:', jwk.kty, 'alg:', jwk.alg, 'k length:', jwk.k.length);
// Later: rebuild the same key from the stored JWK
const revived = await crypto.subtle.importKey(
'jwk',
jwk,
'AES-GCM',
true,
['encrypt', 'decrypt'],
);
const roundtrip = await crypto.subtle.exportKey('jwk', revived);
console.log('same material:', roundtrip.k === jwk.k);
console.log('usages:', revived.usages.join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
kty: oct alg: A256GCM k length: 43
same material: true
usages: encrypt,decryptHow the code works
Await points sequence the asynchronous work; a rejection lands at the awaiting line.
Top-level bindings key, jwk, revived, roundtrip hold the demo state — nothing sits inside a function scope.
What to watch for
- It is dependency-free in the strict sense — the import list, if any, is empty of packages.
- The snippet leans on
crypto— browser-only surfaces a bare Node process cannot provide.
Using it
The output lines announce the steps: kty:, same material:, usages:.
Key statements
const roundtrip = await crypto.subtle.exportKey('jwk', revived);
const jwk = await crypto.subtle.exportKey('jwk', key);
const revived = await crypto.subtle.importKey(
'jwk',
jwk,
'AES-GCM',
true,
['encrypt', 'decrypt'],
);
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- Is there an install step between copy and run?
- No. Between copying and running there is nothing left to do. Its state lives in module-level bindings: `key`, `jwk`, `revived`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.