如何在 NodeJS 中使用 ssh2 库生成 SSH 公钥和私钥
以下代码是基于 Promise 的 ssh2 utils.generateKeyPair() 包装器:
ssh_generate_keypair.js
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;
}ed25519 密钥的使用示例:
generate_ed25519_example.js
SSHGenerateAndSaveKeyPairPromise('ed25519', {
privateKeyPath: 'id_ed25519',
publicKeyPath: 'id_ed25519.pub'
}).then(keys => {
console.log("Successfully generated ed25519 keys");
}).catch(err => {
console.log(err);
});rsa 密钥的使用示例:
generate_rsa_example.js
SSHGenerateAndSaveKeyPairPromise('rsa', {
bits: 8192,
privateKeyPath: 'id_rsa',
publicKeyPath: 'id_rsa.pub'
}).then(keys => {
console.log("Successfully generated RSA keys");
}).catch(err => {
console.log(err);
});Check out similar posts by category:
NodeJS
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow