How to create a pair private/public keys using Node.js crypto?

Dail picture Dail · Dec 15, 2011 · Viewed 68.8k times · Source

I have to generate two keys (private and public) to encrypt a text with the public and let the user with the private key decrypt the text.

Is it possible with the module Crypto?

Answer

Nelson Owalo picture Nelson Owalo · Oct 12, 2018

nodejs v10.12 now supports this natively with crypto.generateKeyPair

const { generateKeyPair } = require('crypto');
generateKeyPair('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret'
  }
}, (err, publicKey, privateKey) => {
  // Handle errors and use the generated key pair.
});