Use PEM keys

Read the -----BEGIN …----- key files that OpenSSL, cloud consoles and identity providers hand you, and write a JWK back out as PEM.

PEM is the text format most key tools speak: a label line, base64 in the middle, an end line. You meet it when OpenSSL generates a key, when a cloud KMS or an identity provider lets you download one, or when a partner sends you their public key or certificate. importPEM turns it into a JWK that sign(), verify() and the rest accept, and exportPEM goes the other way for a tool that only takes PEM.

#Before you start

  • PEM doesn't say which algorithm a key is for, so importPEM always takes one, and stamps it on the JWK as alg.
  • PEM is for key pairs only: RSA, EC, Ed25519 and X25519 keys. A secret (oct key) has no PEM form.
  • Three labels are read, and older ones are not:
LabelFormatWhat you get
-----BEGIN PRIVATE KEY-----PKCS#8the private JWK
-----BEGIN PUBLIC KEY-----SPKIthe public JWK
-----BEGIN CERTIFICATE-----X.509the certificate's public key, as a JWK

RSA PRIVATE KEY (PKCS#1) and EC PRIVATE KEY (SEC1) need converting to PKCS#8 first, see Convert an older key file.

#Sign with a key from a PEM file

Read the private key once at start-up, give it a kid, and sign with the JWK:

pem-key.ts
import { importPEM } from "unjwt/jwk";
import { sign } from "unjwt/jws";

const pem = process.env.SIGNING_KEY_PEM; // "-----BEGIN PRIVATE KEY-----…"
if (!pem) throw new Error("SIGNING_KEY_PEM is not set");

const signingKey = await importPEM(pem, "RS256", {
  pemType: "pkcs8",
  jwkParams: { kid: "2026-10" },
});

export function issueToken(userId: string) {
  return sign({ sub: userId }, signingKey, { expiresIn: "15m" });
}
  • pemType: "pkcs8": the label has to match, so a public key or a certificate pasted into this variable fails at start-up. It also types the result as a private JWK.
  • jwkParams: PEM carries no name, so add the kid your verifiers look for. Without one, tokens carry no kid in the header.
  • Wrong algorithm: an EC key read as RS256, or a P-256 key read as ES384, throws ERR_JWK_INVALID.

The verifier side reads the matching PUBLIC KEY or CERTIFICATE the same way: await importPEM(publicPem, "RS256"). From a certificate, only the public key is kept; its subject, issuer, dates and signature are not read or checked, so importPEM is not certificate validation.

#Make a key pair with OpenSSL

OpenSSL writes PKCS#8 and SPKI by default:

openssl genpkey -algorithm RSA -pkeyopt rsa_keygen_bits:2048 -out private.pem
openssl pkey -in private.pem -pubout -out public.pem

For ES256 use -algorithm EC -pkeyopt ec_paramgen_curve:P-256, for Ed25519 -algorithm ed25519. Keep private.pem in your secret store and hand out public.pem.

#Convert an older key file

A file that starts with -----BEGIN RSA PRIVATE KEY----- or -----BEGIN EC PRIVATE KEY----- is refused. Convert it once:

openssl pkcs8 -topk8 -nocrypt -in legacy.pem -out private.pem

#Write a JWK as PEM

exportPEM writes PKCS#8 for a private JWK and SPKI for a public one, in 64-character lines:

import { exportPEM } from "unjwt/jwk";

await exportPEM(publicKey); // "-----BEGIN PUBLIC KEY-----\nMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE…"

It doesn't write certificates: a certificate needs a subject and a CA's signature that a JWK doesn't have. Asking for SPKI from a private JWK throws instead of dropping its private members; pass the pair's publicKey.

#When it fails

SituationWhat happens
No label importPEM reads (PKCS#1, SEC1, anything else) and no pemTypeThrows ERR_JWK_INVALID.
The label differs from pemTypeThrows ERR_JWK_INVALID.
More than one block, or anything but whitespace after the blockThrows ERR_JWK_INVALID.
The body is damaged, or the key doesn't fit alg (wrong type or curve)Throws ERR_JWK_INVALID.
alg has no PEM form, such as HS256, or exportPEM gets an oct keyThrows ERR_JWK_UNSUPPORTED.
exportPEM gets a JWK without alg and no alg optionThrows ERR_JWK_INVALID.
pemFormat contradicts the key ("spki" for a private JWK)Throws ERR_JWK_INVALID.
pem isn't a string, or jwkParams sets alg, kty, key_ops, ext or a key memberThrows ERR_INVALID_OPTION.

Text before the block is ignored (RFC 7468 §2), so a file with a comment above the label still reads. Handle errors lists every code.

#Options

importPEM(pem, alg, options) and exportPEM(jwk, options):

OptionDefaultNotes
pemTyperead from the labelimportPEM. "pkcs8", "spki" or "x509"; must match the label.
jwkParamsnoneimportPEM. Metadata merged onto the JWK: kid, use, x5c, …
pemFormat"pkcs8" for a private JWK, else "spki"exportPEM.
algthe JWK's algexportPEM. Needed for a JWK without one.

alg on importPEM is any RSA, EC or OKP algorithm: RS*, PS*, RSA-OAEP*, ES*, ECDH-ES*, Ed25519, EdDSA. An X25519 key read for ECDH-ES* becomes an OKP JWK.

#Going further

  • Keep a private key from staying readable: the JWK importPEM returns holds the key material; pass it to importKey for a CryptoKey that can't be exported.
  • Publish the public half: Use a JWK Set.
  • Sign sessions with a PEM key: Configure a session.
  • No PEM involved: Generate keys makes JWKs directly.