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 anoctJWK or aUint8Array. - A JWK's
algis binding (RFC 7517 §4.4). A key that saysES256is used forES256and nothing else. - An RSA, EC or OKP JWK without
algneeds 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 pass | You get |
|---|---|
| An RSA, EC or OKP JWK | A CryptoKey for its alg. A private key is not extractable unless you pass extractable: true. |
An oct JWK | The secret as a Uint8Array, after a length check against its algorithm. |
An oct JWK with asCryptoKey | A CryptoKey for the Web Crypto algorithm and usage you name, not extractable by default. |
A CryptoKey or a Uint8Array | The same object, unchanged. |
| A string | Throws 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 onoctsecrets, which have no halves.verify()andencrypt()already expect public keys,sign()anddecrypt()private ones.alg: the algorithm you'll use the key for. A JWK whose ownalgdiffers is refused rather than silently used for either; one withoutalgis imported for this one, when its key type can serve it. AnoctJWK underES256, or an EC JWK underHS256, is refused. The one exception is anoctkey whosealgis a content encryption algorithm such asA256GCM: that key is meant fordir, and imports under it.- Secret length: an
octkey shorter than its algorithm needs is refused.HS256,HS384andHS512need 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
extorkey_ops: they describe theCryptoKey, not the key, so they're left out. algcomes from Web Crypto: EC and OKP keys export without one, and an AES-GCM key made forA256GCMKWexports asA256GCM. When the label matters, make the key withgenerateJWK, which writes the algorithm you asked for.- Not extractable, not exportable: a private key imported from a JWK is not extractable by default, and
exportJWKrefuses 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:
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)); // truekid, 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); // trueUtilities lists every guard.
#When it fails
| Situation | What happens |
|---|---|
| The key is a string | Throws ERR_JWK_INVALID. |
An RSA, EC or OKP JWK has no alg and you passed none | Throws ERR_JWK_INVALID. |
The alg you pass differs from the JWK's | Throws ERR_JWK_INVALID. |
The JWK has no alg and its kty can't serve the one you pass, such as an oct key under ES256 | Throws ERR_JWK_INVALID. |
An oct secret is too short or the wrong size for its algorithm | Throws ERR_JWK_INVALID. |
The key is the wrong half for expect | Throws ERR_JWK_INVALID. |
The JWK's crv or key_ops doesn't fit the algorithm | Throws ERR_JWK_INVALID. |
asCryptoKey without algorithm and usage | Throws ERR_JWK_INVALID. |
exportJWK gets a key that isn't extractable | Throws ERR_JWK_INVALID. |
exportJWK gets something that isn't a CryptoKey, or metadata sets alg, kty, key_ops, ext or a key member | Throws ERR_INVALID_OPTION. |
toPublicJWK gets an oct key, or a JWK missing its public members | Throws ERR_JWK_INVALID. |
thumbprint gets a JWK missing a required member, or an unknown hash | Throws 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:
| Option | Default | Notes |
|---|---|---|
alg | the JWK's own alg | Required for an RSA, EC or OKP JWK without one. Must match the JWK's when both exist. |
expect | none | "public" or "private". No effect on oct keys. |
extractable | false for private, true for public | A JWK with ext: false stays not extractable. |
asCryptoKey | none | oct JWK only: import as a CryptoKey instead of bytes. |
algorithm, usage | none | Required 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 aCryptoKeydoesn'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.