Node.js函数使用Open SSL生成RSA密钥

我使用Node.js作为服务器端语言,我想为任何在我的网站上注册的用户生成一个RSA密钥对。 我正在使用一个称为密钥对的模块。 对于小尺寸的密钥来说,它工作的很好,但是当我生成大小为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或一个数组作为结果的函数来保存公钥和私钥。

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

试试这个..把代码稍微移了一下。 使用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); 

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

这是非常容易使用 ,它是asynchronous的

 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,而是使用OpenSSL中的 ssh-keygen (来自OpenSSH )。 没有直接的安全差异(请参阅此处以获取更多信息 )。

PS:查看构成rsa-json的唯一48行代码 。


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

  • 不是asynchronous的
  • 没有维护, 最后一次提交是从2012年12月21日
  • 该项目是沉重的,它做了太多东西,如含糖的东西(base64编码等)。
  • 它内嵌了C ++ OpenSSL包装器,在安装过程中初始化。

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