Import and export keys

Turn a JWK into a CryptoKey and back, check a key before you rely on it, derive a public half, and name a key by its thumbprint.

A JWK is the key written down; a CryptoKey is the same key loaded into the runtime's Web Crypto, ready to sign or decrypt but not something you can save. You rarely convert by hand: sign(), verify(), encrypt() and decrypt() accept a JWK and load it themselves. You reach for importKey and exportJWK when your own Web Crypto code needs a key, when you want a bad key to fail at start-up, or when a key arrives as a CryptoKey and you need it as JSON.

#Before you start

  • A string is never a key here. PEM text goes to importPEM, a password to Derive keys from a password, and a shared secret becomes an oct JWK or a Uint8Array.
  • A JWK's alg is binding (RFC 7517 §4.4). A key that says ES256 is used for ES256 and nothing else.
  • An RSA, EC or OKP JWK without alg needs one from you when you import it.

#Turn a JWK into a CryptoKey

importKey returns what Web Crypto can use. For a public or private JWK that's a CryptoKey; for an oct JWK it's the secret's bytes:

import { importKey } from "unjwt/jwk";

await importKey(publicKey); // CryptoKey { type: "public", algorithm: { name: "ECDSA", namedCurve: "P-256" }, usages: ["verify"] }
await importKey(secret); // Uint8Array(64), the bytes of an HS256 secret's `k`
You passYou get
An RSA, EC or OKP JWKA CryptoKey for its alg. A private key is not extractable unless you pass extractable: true.
An oct JWKThe secret as a Uint8Array, after a length check against its algorithm.
An oct JWK with asCryptoKeyA CryptoKey for the Web Crypto algorithm and usage you name, not extractable by default.
A CryptoKey or a Uint8ArrayThe same object, unchanged.
A stringThrows ERR_JWK_INVALID.

The result type follows what you pass, so a JWK you typed as public comes back as CryptoKey without a cast.

#Check a key before you rely on it

Two options turn a misplaced key into an error at start-up rather than a failed request later:

await importKey(signingKey, { alg: "ES256", expect: "private" });
  • expect: "private" refuses a public key, "public" refuses a private one, so a private key never ends up somewhere you publish. It has no effect on oct secrets, which have no halves. verify() and encrypt() already expect public keys, sign() and decrypt() private ones.
  • alg: the algorithm you'll use the key for. A JWK whose own alg differs is refused rather than silently used for either; one without alg is imported for this one, when its key type can serve it. An oct JWK under ES256, or an EC JWK under HS256, is refused. The one exception is an oct key whose alg is a content encryption algorithm such as A256GCM: that key is meant for dir, and imports under it.
  • Secret length: an oct key shorter than its algorithm needs is refused. HS256, HS384 and HS512 need at least 32, 48 and 64 bytes (RFC 7518 §3.2); the AES algorithms need their exact size.

Ed448 and X448 keys are not supported, and an EC or OKP key's crv has to fit the algorithm.

#Export a CryptoKey as a JWK

exportJWK writes an extractable CryptoKey out as JSON, with any metadata you add:

import { exportJWK, generateKey } from "unjwt/jwk";

const { publicKey } = await generateKey("RS256");
await exportJWK(publicKey, { kid: "2026-10", use: "sig" });
// { alg: "RS256", kty: "RSA", n: "t8w0FrT1…", e: "AQAB", kid: "2026-10", use: "sig" }
  • No ext or key_ops: they describe the CryptoKey, not the key, so they're left out.
  • alg comes from Web Crypto: EC and OKP keys export without one, and an AES-GCM key made for A256GCMKW exports as A256GCM. When the label matters, make the key with generateJWK, which writes the algorithm you asked for.
  • Not extractable, not exportable: a private key imported from a JWK is not extractable by default, and exportJWK refuses it.

#Derive the public half of a stored private key

Keep both halves of a pair when you can. When a deployment has room for one secret and you store the private JWK alone, toPublicJWK gives you its public half at start-up:

public-half.ts
import { toPublicJWK, type JWK_EC_Public } from "unjwt/jwk";
import { verify } from "unjwt/jws";
import { signingKey } from "./signing-key.ts";

/** Derived once at start-up: the same JWK without its private members. */
export const verifyKey: JWK_EC_Public<"ES256"> = toPublicJWK(signingKey);

export async function readToken(token: string) {
  const { payload } = await verify(token, verifyKey);
  return payload;
}

toPublicJWK drops the private members (d, and p, q, dp, dq, qi, oth on RSA) and keeps the rest, kid and alg included. A key_ops becomes its public counterpart: sign turns into verify, decrypt into encrypt, unwrapKey into wrapKey. The result equals the publicKey the pair was generated with. It runs synchronously and throws ERR_JWK_INVALID for an oct key, which has no public half.

#Name a key by its thumbprint

thumbprint computes the RFC 7638 digest of a key's public members. It's the default kid of generated keys, and a stable name for a key you received without one:

import { thumbprint } from "unjwt/jwk";

await thumbprint(publicKey); // "OC-A6_UJPq51uzNi1_xboje0-vKvPxh2Y5-USbmAZnM"
(await thumbprint(privateKey)) === (await thumbprint(publicKey)); // true

kid, use, alg and the private members don't count, so both halves of a pair share a thumbprint and relabelling a key doesn't change it. Pass { hash: "SHA-384" } or "SHA-512" for a longer digest.

#Tell keys apart

The type guards in unjwt/utils check a value you parsed before you use it:

import { isJWK, isPrivateJWK, isPublicJWK, isSymmetricJWK } from "unjwt/utils";

isPrivateJWK(privateKey); // true
isPublicJWK(privateKey); // false
isSymmetricJWK(secret); // true

Utilities lists every guard.

#When it fails

SituationWhat happens
The key is a stringThrows ERR_JWK_INVALID.
An RSA, EC or OKP JWK has no alg and you passed noneThrows ERR_JWK_INVALID.
The alg you pass differs from the JWK'sThrows ERR_JWK_INVALID.
The JWK has no alg and its kty can't serve the one you pass, such as an oct key under ES256Throws ERR_JWK_INVALID.
An oct secret is too short or the wrong size for its algorithmThrows ERR_JWK_INVALID.
The key is the wrong half for expectThrows ERR_JWK_INVALID.
The JWK's crv or key_ops doesn't fit the algorithmThrows ERR_JWK_INVALID.
asCryptoKey without algorithm and usageThrows ERR_JWK_INVALID.
exportJWK gets a key that isn't extractableThrows ERR_JWK_INVALID.
exportJWK gets something that isn't a CryptoKey, or metadata sets alg, kty, key_ops, ext or a key memberThrows ERR_INVALID_OPTION.
toPublicJWK gets an oct key, or a JWK missing its public membersThrows ERR_JWK_INVALID.
thumbprint gets a JWK missing a required member, or an unknown hashThrows ERR_JWK_INVALID or ERR_INVALID_OPTION.

Handle errors lists every code.

#Options

importKey(key, options) takes an algorithm name as a shorthand for { alg }, or:

OptionDefaultNotes
algthe JWK's own algRequired for an RSA, EC or OKP JWK without one. Must match the JWK's when both exist.
expectnone"public" or "private". No effect on oct keys.
extractablefalse for private, true for publicA JWK with ext: false stays not extractable.
asCryptoKeynoneoct JWK only: import as a CryptoKey instead of bytes.
algorithm, usagenoneRequired with asCryptoKey, as Web Crypto takes them.

exportJWK(key, metadata) merges kid, use, x5c, x5t, x5t#S256 and x5u onto the result. thumbprint(jwk, { hash }) defaults to "SHA-256".

#Going further

  • A JWK whose type you know: exportJWK<JWK_RSA_Public>(key) types the result, since a CryptoKey doesn't tell the compiler.
  • Imported keys are reused across calls when you pass the same JWK object: The key cache.
  • PEM files: Use PEM keys.