PEM conversion
PEM (-----BEGIN PRIVATE KEY----- / -----BEGIN PUBLIC KEY-----) is the key format used by OpenSSL, SSH, most CLI tools, and many legacy systems. unjwt converts between JWK and PEM with importPEM and exportPEM.
import { importPEM, exportPEM } from "unjwt/jwk";
importPEM
importPEM(pem, alg, options?)
Parses a PEM string and returns it as a JWK. The PEM type is inferred from the -----BEGIN <X>----- label:
| PEM label | Inferred pemType |
|---|---|
-----BEGIN PRIVATE KEY----- | "pkcs8" — private key |
-----BEGIN PUBLIC KEY----- | "spki" — public key |
-----BEGIN CERTIFICATE----- | "x509" — X.509 certificate |
import.ts
import { importPEM } from "unjwt/jwk";
import { readFile } from "node:fs/promises";
const pem = await readFile("./rsa-private.pem", "utf-8");
const jwk = await importPEM(pem, "RS256", {
extractable: true,
jwkParams: { kid: "rsa-main", use: "sig" },
});
Options
| Option | Default | Effect |
|---|---|---|
pemType | Inferred from label | Override explicitly if the label is missing |
extractable | true | Web Crypto extractable flag |
jwkParams | — | Extra JWK metadata (kid, use, ...) |
Throws ERR_JWK_INVALID if:
- The PEM has no recognizable label and
pemTypeis not supplied. - The label doesn't match the requested or inferred
pemType.
exportPEM
exportPEM(jwk, options?)
Converts a JWK back to a PEM-encoded string. The PEM format is inferred from the JWK shape:
- JWK has
d(or an equivalent private component) →"pkcs8"(private). - No
d→"spki"(public).
export.ts
import { exportPEM } from "unjwt/jwk";
const pem = await exportPEM(jwk);
// "-----BEGIN PRIVATE KEY-----\n...base64...\n-----END PRIVATE KEY-----\n"
Options
| Option | Default | Effect |
|---|---|---|
pemFormat | Inferred from JWK | "pkcs8" or "spki" — cert export is not supported |
alg | jwk.alg | Algorithm hint used when jwk.alg is absent |
X.509 certificate export is intentionally not supported. A certificate requires metadata (subject, issuer, validity period, extensions) and a CA signature — none of which a JWK carries. If you need a certificate, generate it with a PKI tool (OpenSSL,
step-ca, your CA's API) and import it with importPEM().Deprecated aliases
Earlier unjwt versions exposed positional equivalents:
// Deprecated — still work, emit IDE deprecation hints
importFromPEM(pem, pemType, alg, options?);
exportToPEM(jwk, pemFormat, alg?);
These remain for backward compatibility but you should migrate to importPEM / exportPEM on touch.
See also
- Importing & exporting → — for JWK/CryptoKey/bytes.
- Generating keys →.