【问题标题】:Node.js function to generate RSA keys using Open SSL使用 Open SSL 生成 RSA 密钥的 Node.js 函数
【发布时间】:2013-09-25 11:10:41
【问题描述】:

我使用 Node.js 作为服务器端语言,我想为在我的网站上注册的任何用户生成一个 RSA 密钥对。我正在使用一个名为keypair 的模块。它适用于小尺寸的密钥,但是当我生成大小为 2048 的密钥时,执行它需要很长时间,所以我想使用 Node 的 child_process 直接从 Node.js 使用 Open SSL,如下面的脚本中所述:

var cp = require('child_process')
  , assert = require('assert');

var privateKey, publicKey;
publicKey = '';
cp.exec('openssl genrsa 2048', function(err, stdout, stderr) {
  assert.ok(!err);
  privateKey = stdout;
  console.log(privateKey);
  makepub = cp.spawn('openssl', ['rsa', '-pubout']);
  makepub.on('exit', function(code) {
    assert.equal(code, 0); 
    console.log(publicKey);
  });
  makepub.stdout.on('data', function(data) {
    publicKey += data;
  });
  makepub.stdout.setEncoding('ascii');
  makepub.stdin.write(privateKey);
  makepub.stdin.end();  
});

这在密钥对生成方面比 Node.js 密钥对模块工作得更快,所以我遇到的问题是我不理解这段代码(如果它在服务器端写入文件并从中读取密钥)或不是?),我想把这个脚本变成一个函数,返回一个 JSON 或一个数组作为结果,保存公钥和私钥。

所以欢迎任何建议,提前谢谢。

【问题讨论】:

  • node.js 不是一种语言。以防万一。

标签: node.js openssl rsa


【解决方案1】:

试试这个.. 稍微移动了代码。使用 tmp 文件,该文件已被删除,可能没有 tmp 文件也可以完成,但这应该可以。

var cp = require('child_process')
  , assert = require('assert')
  , fs = require('fs')
  ;

// gen pub priv key pair
function genKeys(cb){
    // gen private
    cp.exec('openssl genrsa 2048', function(err, priv, stderr) {
      // tmp file
      var randomfn = './' + Math.random().toString(36).substring(7);
      fs.writeFileSync(randomfn, priv);
      // gen public
      cp.exec('openssl rsa -in '+randomfn+' -pubout', function(err, pub, stderr) {
           // delete tmp file
           fs.unlinkSync(randomfn);
           // callback
           cb(JSON.stringify({public: pub, private: priv}, null, 4));
      });

    });
}

genKeys(console.log);

【讨论】:

  • 工作真棒,非常感谢。只是出于好奇,您所说的“可能在没有 tmp 文件的情况下可以完成”是什么意思?
  • 将私钥直接传送到第二个命令,无需将临时文件写入磁盘。但是没有看到如何做到这一点。
【解决方案2】:

您可以简单地使用小的rsa-json 模块

它真的易于使用而且它是异步的

var createRsaKeys = require('rsa-json');

createRsaKeys({bits: 1024}, function(err, keyPair) {
    console.log(keyPair.private);
    console.log(keyPair.public);
});

rsa-json 不直接使用OpenSSL RSA_generate_key,而是使用ssh-keygen(来自OpenSSH),它是OpenSSL 的包装器。没有直接的安全差异(请参阅this for more information)。

PS:看看唯一的 48 lines of code 构成 rsa-json。


如果你真的想使用 OpenSSL,你可以看看ursa module 但是:

  • 不是异步的
  • 未维护,last commit 来自 2012 年 12 月 21 日
  • 这个项目很重,它做了太多的事情,比如含糖的东西(base64 编码等)。
  • 它在其中嵌入了 C++ OpenSSL 包装器,在安装过程中进行了初始化。

PS:keypair 使用原生 JS,这就是为什么它很慢。不推荐使用不擅长执行 CPU 密集型操作(但擅长非阻塞事件)的 Node.js。

【讨论】:

    猜你喜欢
    • 2012-11-07
    • 1970-01-01
    • 1970-01-01
    • 2016-09-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多