Sometimes, we want to create a pair of private and public keys using Node.js crypto.
In this article, we’ll look at how to create a pair of private and public keys using Node.js crypto.
How to create a pair of private and public keys using Node.js crypto?
To create a pair of private and public keys using Node.js crypto, we can use 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 generateKeyPair with 'rsa' to generate a pair of RSA keys.
We set the settings for the public key in publicKeyEncoding and set the settings for the private key in privateKeyEncoding.
Then we get the public and private from the publicKey and privateKey parameter in the callback
Conclusion
To create a pair of private and public keys using Node.js crypto, we can use the generateKeyPair function.