Categories
JavaScript Answers

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

Spread the love

To create a pair private/public keys using Node.js crypto, we call the generateKeyPair function.

For instance, we write

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) => {
    //...
  }
);

to call generateKetPair with 'rsa' to generate a pair of public and private keys.

We set the cipher and passphrase for the private key.

And we set the format for both keys.

Then we get the public and private key from the publicKey and privateKey parameters in the callback.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *