ecdsa.com

Generate a key pair · Node.js

How to generate an ECDSA key pair in Node.js

Generating an ECDSA key pair in Node.js is built into node:crypto: one call creates the pair, and the export options decide the container format. Use PKCS#8 for the private key and SPKI for the public key unless something downstream demands otherwise.

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

Same recipe in:Node.jsPythonGoOpenSSLWebCrypto
generate-key.mjs — P-256 pair, standard PEM containers
import { generateKeyPairSync } from "node:crypto";
 
const { privateKey, publicKey } = generateKeyPairSync("ec", {
namedCurve: "P-256", // aka prime256v1 / secp256r1
});
 
const privPem = privateKey.export({ type: "pkcs8", format: "pem" });
const pubPem = publicKey.export({ type: "spki", format: "pem" });
console.log(privPem); // -----BEGIN PRIVATE KEY-----
console.log(pubPem); // -----BEGIN PUBLIC KEY-----
the same key as JWK (for JOSE / WebCrypto interop)
console.log(privateKey.export({ format: "jwk" }));
// { kty: 'EC', crv: 'P-256', d: '...', x: '...', y: '...' }

How it works

  1. generateKeyPairSync("ec", { namedCurve }) returns live KeyObjects — usable for signing immediately, no export required.
  2. type: "pkcs8" gives the modern BEGIN PRIVATE KEY container; type: "sec1" exists for the legacy BEGIN EC PRIVATE KEY layout.
  3. type: "spki" is the universal public key container that every stack on this site accepts.
  4. There is also a callback-based generateKeyPair for async contexts — same options.

Gotchas

  • namedCurve accepts both naming families: "P-256" and "prime256v1" are the same curve. Node also supports "secp256k1" — WebCrypto in the browser does not, so don't generate secp256k1 keys destined for it.
  • The exported private PEM is unencrypted. Either pass cipher/passphrase to export, or make sure the file lands with 0600 permissions outside any repository.
  • P-256 signs with SHA-256 by convention; if you pick P-384, plan for SHA-384 everywhere — mixed pairings verify fine within one stack and then surprise the next one.

Related recipes