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.

JavascriptSecurity Boundaries

Code

javascriptsnippet
23 lines
// 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,decrypt

How 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

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`.