'Promisified crypto in node.js

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.



Solution 1:[1]

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);
})();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Shankar