Home > Back-end >  Promisified crypto in node.js
Promisified crypto in node.js

Time:05-07

When we check the doc of crypto from https://nodejs.org/api/crypto.html#cryptogeneratekeypairtype-options-callback, we see this sentence.

If this method is invoked as its util.promisify()ed version, it returns a Promise for an Object with publicKey and privateKey properties.

Then, how to use the promisified one? We tried ten more ways and none of them worked.

CodePudding user response:

You can use it like this. It resolves to object which contain publicKey and privateKey

const util = require('util');
const crypto = require('crypto');

const gen = util.promisify(crypto.generateKeyPair);
(async () => {
  const res = await gen('rsa', {
    modulusLength: 4096,
    publicKeyEncoding: {
      type: 'spki',
      format: 'pem'
    },
    privateKeyEncoding: {
      type: 'pkcs8',
      format: 'pem',
      cipher: 'aes-256-cbc',
      passphrase: 'top secret'
    }
  });
  console.log(res);
})();
  • Related