Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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-----`);
@codermapuche

This comment has been minimized.

Copy link

codermapuche commented Sep 21, 2018

For prime256v1 curve:

console.log(`-----BEGIN EC PRIVATE KEY-----
${Buffer.from(`30770201010420${keyPair.getPrivateKey('hex')}A00A06082A8648CE3D030107A144034200${keyPair.getPublicKey('hex')}`, 'hex').toString('base64')}
-----END EC PRIVATE KEY-----`);

Note the EC keyword

@codermapuche

This comment has been minimized.

Copy link

codermapuche commented Sep 21, 2018

How find this numbers:

  1. run openssl ecparam -name prime256v1 -genkey -noout -out key.pem with curve name desired
  2. upload to https://lapo.it/asn1js/ or open with hex editor
  3. find control characters and key blocks (compare lengths with your own key in hex format)
  4. Extract control characters and replace in the code of this git
  5. Generate a pem of test and validate it with the tool of step 2
  6. Repeat steps 3 to 5 while not success
@mvasilkov

This comment has been minimized.

Copy link

mvasilkov commented Dec 15, 2018

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

@mfaisaltariq

This comment has been minimized.

Copy link

mfaisaltariq commented Jun 23, 2019

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
You can’t perform that action at this time.