How to create a privateKey/publicKey pair of KeyObject return type and 256 bits length in Node.js?

Viewed 28

How to create a privateKey/publicKey pair of KeyObject return type and 256 bits length in Node.js? Kindly ask you to provide a working example. I tried this one:

const { generateKeyPair } = require('node:crypto');
generateKeyPair(
    'rsa',
    {
      modulusLength: 1024,
      publicKeyEncoding: {
        type: 'spki',
        format: 'pem'
      },
      privateKeyEncoding: {
        type: 'pkcs8',
        format: 'pem',
        cipher: 'aes-256-cbc',
        passphrase: secret
      }
    },
    (err, publicKey, privateKey) => {
      if (err) res.end(JSON.stringify(err));

      console.log('private: ', privateKey);
      console.log('public: ', publicKey);
    }
  );

But when I change modulusLength value to the required 256 bits I get an error. I need it for JOSE JWE secret.

1 Answers

I believe you don't actually want a 256 bit RSA key. You need a 256 bit symmetric secret based on the other questions you've opened. You also don't need a KeyObject, a Uint8Array / Buffer will do fine for the jose library you're attempting to use (docs).

Anyway. You can generate a random KeyObject (of type "secret") like so.

const crypto = require('node:crypto')

// option 1
crypto.generateKey('aes', { length: 256 }, (err, secret) => {
  if (err) {
    // handle err
  } else {
    console.log(secret)
  }
})


// option 2
crypto.createSecretKey(crypto.randomBytes(32))

crypto.createSecretKey is also how you would re-instantiate a secret KeyObject based on random bytes you have elsewhere stored and serialized.

Related