Skip to content

Instantly share code, notes, and snippets.

@canterberry
Created April 26, 2018 23:15
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save canterberry/bf190ae6402265751e51725be535a4e4 to your computer and use it in GitHub Desktop.
Save canterberry/bf190ae6402265751e51725be535a4e4 to your computer and use it in GitHub Desktop.
Export PEM-encoded EC key pair (ECDH, ECDSA)
// (Buffer is available in Node.js as a global, but we require it this way for compatibility)
// See: https://nodejs.org/api/buffer.html#buffer_buffer
const { Buffer } = require('buffer');
const crypto = require('crypto');
const keyPair = crypto.createECDH('secp256k1');
keyPair.generateKeys();
// Print the PEM-encoded private key
console.log(`-----BEGIN PRIVATE KEY-----
${Buffer.from(`308184020100301006072a8648ce3d020106052b8104000a046d306b0201010420${keyPair.getPrivateKey('hex')}a144034200${keyPair.getPublicKey('hex')}`, 'hex').toString('base64')}
-----END PRIVATE KEY-----`);
// Print the PEM-encoded public key
console.log(`-----BEGIN PUBLIC KEY-----
${Buffer.from(`3056301006072a8648ce3d020106052b8104000a034200${keyPair.getPublicKey('hex')}`, 'hex').toString('base64')}
-----END PUBLIC KEY-----`);
@mvasilkov
Copy link

Thanks! Amazing how this isn't explained in the docs at all, and not available in the standard crypto module for that matter.

@mfaisaltariq
Copy link

Hi, I'm sorry I'm new to this but can I know how can I generate a Public Key PEM for an ECDSA P-256 curve using an SPKI or JWK?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment