How to generate SSH public & private key in NodeJS using ssh2 library
The following code is a Promise
based wrapper around ssh2’s utils.generateKeyPair()
:
const { utils: { generateKeyPair } } = require('ssh2');
const {writeFile} = require('fs/promises');
/**
* ssh2's generateKeyPair as promise
*/
function SSHGenerateKeyPairPromise(keytype="ed25519", opts = {}) {
return new Promise((resolve, reject) => {
generateKeyPair(
keytype, opts,
(err, keys) => {
if (err) { return reject(err) };
return resolve(keys);
}
);
});
}
/**
* Run SSHGenerateKeyPairPromise() and save the keys to
* opts.privateKeyPath and opts.publicKeyPath
* @returns The generated keys
*/
async function SSHGenerateAndSaveKeyPairPromise(keytype="ed25519", opts = {}) {
// Check if opts.privateKeyPath and opts.publicKeyPath are set
if (!opts.privateKeyPath || !opts.publicKeyPath) {
throw new Error("opts.privateKeyPath and opts.publicKeyPath must be set");
}
const keys = await SSHGenerateKeyPairPromise(keytype, opts);
//Save keys to opts.privateKeyPath and opts.publicKeyPath using fs.promise
await writeFile(opts.privateKeyPath, keys.private);
await writeFile(opts.publicKeyPath, keys.public);
return keys;
}
Usage example for ed25519
keys:
SSHGenerateAndSaveKeyPairPromise('ed25519', {
privateKeyPath: 'id_ed25519',
publicKeyPath: 'id_ed25519.pub'
}).then(keys => {
console.log("Successfully generated ed25519 keys");
}).catch(err => {
console.log(err);
});
Usage example for rsa
keys:
SSHGenerateAndSaveKeyPairPromise('rsa', {
bits: 8192,
privateKeyPath: 'id_rsa',
publicKeyPath: 'id_rsa.pub'
}).then(keys => {
console.log("Successfully generated RSA keys");
}).catch(err => {
console.log(err);
});