You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在纯原生Node.js中实现ssh-keygen -t rsa -b 4096功能?

Can I generate RSA keys like ssh-keygen -t rsa -b 4096 in pure native Node.js?

Absolutely! You can totally generate RSA keys equivalent to what ssh-keygen -t rsa -b 4096 produces using only Node.js's built-in crypto module—no external tools or dependencies needed. The module has all the functionality you need to create, encode, and format keys to match SSH's requirements.

Here's a practical, step-by-step implementation:

1. Generate the RSA key pair

Use crypto.generateKeyPairSync (or the async crypto.generateKeyPair for non-blocking workflows) to create your 4096-bit RSA keys. We'll use PKCS#1 encoding for both keys, which matches ssh-keygen's default RSA output.

const crypto = require('crypto');
const fs = require('fs');

// Generate 4096-bit RSA key pair
const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', {
  modulusLength: 4096, // Matches the `-b 4096` flag from ssh-keygen
  publicKeyEncoding: {
    type: 'pkcs1',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs1',
    format: 'pem'
    // Optional: Encrypt the private key (like ssh-keygen -o)
    // cipher: 'aes-256-cbc',
    // passphrase: 'your-secure-passphrase-here'
  }
});

2. Convert the public key to OpenSSH format

The crypto module's default PEM public key uses PKCS#1 formatting, but SSH expects the familiar ssh-rsa prefix format. We can convert it with a few quick steps:

// Convert PKCS#1 public key to the OpenSSH-compatible format
const spkiPublicKey = crypto.createPublicKey(publicKey).export({
  type: 'spki',
  format: 'pem'
});

// Strip PEM headers and decode the base64 content
const pubKeyBuffer = Buffer.from(
  spkiPublicKey.replace(/-----BEGIN PUBLIC KEY-----\n/, '')
               .replace(/\n-----END PUBLIC KEY-----\n/, ''),
  'base64'
);

// Format into the standard OpenSSH public key string
const sshPublicKey = `ssh-rsa ${pubKeyBuffer.toString('base64')} user@your-hostname`;

3. Save keys to files (optional)

Just like ssh-keygen, you can save the keys to files for direct use with SSH:

// Save private key (restrict permissions to 600 for security!)
fs.writeFileSync('id_rsa', privateKey, { mode: 0o600 });
// Save public key
fs.writeFileSync('id_rsa.pub', sshPublicKey);

console.log('Keys generated successfully!');
console.log('Private key saved to: id_rsa');
console.log('Public key saved to: id_rsa.pub');

Quick notes:

  • For server-side code, use the async crypto.generateKeyPair instead of the sync version to avoid blocking the event loop.
  • Adding the cipher and passphrase options to privateKeyEncoding encrypts your private key, just like ssh-keygen -o—highly recommended for production use.
  • The generated keys are fully SSH-compatible: you can use the private key with Node.js SSH libraries, or copy the public key to a remote server's authorized_keys file just like any other SSH key.

内容的提问来源于stack exchange,提问作者webjay

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:12:03