ecdsa.com

Export public key PEM · Node.js

How to export a public key as PEM in Node.js

Deriving and exporting the public key from an ECDSA private key in Node.js is two calls: createPublicKey lifts the public half out of any private key object, and export serializes it as SPKI PEM — the container every other stack imports directly.

Tested with Node.js 26 (OpenSSL 3.x backend).

Same recipe in:Node.jsPythonGoOpenSSLWebCrypto
export-pub.mjs — private PEM in, public PEM out
import { readFileSync, writeFileSync } from "node:fs";
import { createPrivateKey, createPublicKey } from "node:crypto";
 
const privateKey = createPrivateKey(readFileSync("key.pem"));
const publicKey = createPublicKey(privateKey); // derives the public half
 
const pem = publicKey.export({ type: "spki", format: "pem" });
writeFileSync("pub.pem", pem);
console.log(pem); // -----BEGIN PUBLIC KEY-----
other output shapes from the same KeyObject
publicKey.export({ type: "spki", format: "der" }); // Buffer (binary SPKI)
publicKey.export({ format: "jwk" }); // { kty: 'EC', crv, x, y }

How it works

  1. createPublicKey accepts a private KeyObject (or private PEM directly) and returns the corresponding public key — EC public keys are embedded in, or derivable from, the private key.
  2. type: "spki" selects SubjectPublicKeyInfo — the BEGIN PUBLIC KEY container. This is what OpenSSL, Go, Python and WebCrypto expect.
  3. format: "jwk" is the right shape for JOSE endpoints and WebCrypto's importKey("jwk", …).

Gotchas

  • Node never writes files for you — a script that only calls export and logs will leave no pub.pem behind. Pair export with an explicit write, as above.
  • The PEM label matters downstream: SPKI gives BEGIN PUBLIC KEY. If a consumer demands BEGIN EC PUBLIC KEY (rare, legacy), that is a different serialization Node does not emit — update the consumer, not the label.
  • Copy-pasting PEM through chat or editors can smuggle in smart quotes, CRLF endings or lost final newlines; when a consumer rejects your export, hexdump the file before doubting the key.

Related recipes