如何使用Node.jsencryption创build一对私钥/公钥?

我必须生成两个密钥(私有的和公共的)来与公众encryption文本,并让用户使用私钥解密文本。

模块Crypto可以吗?

谢谢!

下面的代码工作,但我不是一个专业的密码学家,所以这里的一些意见将是有益的。

我使用了ursa RSA模块,而不是encryption。

我担心,如果类似的数据直接encryption,没有AES或类似的通过,那么打破这个可能是微不足道的。 请评论…

var ursa = require('ursa'); var fs = require('fs'); // create a pair of keys (a private key contains both keys...) var keys = ursa.generatePrivateKey(); console.log('keys:', keys); // reconstitute the private key from a base64 encoding var privPem = keys.toPrivatePem('base64'); console.log('privPem:', privPem); var priv = ursa.createPrivateKey(privPem, '', 'base64'); // make a public key, to be used for encryption var pubPem = keys.toPublicPem('base64'); console.log('pubPem:', pubPem); var pub = ursa.createPublicKey(pubPem, 'base64'); // encrypt, with the public key, then decrypt with the private var data = new Buffer('hello world'); console.log('data:', data); var enc = pub.encrypt(data); console.log('enc:', enc); var unenc = priv.decrypt(enc); console.log('unenc:', unenc); 

经过一些进一步的调查http://en.wikipedia.org/w/index.php?title=RSA_%28cryptosystem%29&section=12#Attacks_against_plain_RSA它看起来像ursa已经填充。

使用npm中的encryption模块来生成KeyPair。

 var crypto = require('crypto'); var prime_length = 60; var diffHell = crypto.createDiffieHellman(prime_length); diffHell.generateKeys('base64'); console.log("Public Key : " ,diffHell.getPublicKey('base64')); console.log("Private Key : " ,diffHell.getPrivateKey('base64')); console.log("Public Key : " ,diffHell.getPublicKey('hex')); console.log("Private Key : " ,diffHell.getPrivateKey('hex')); 

以上是一个示例代码片段。 要了解更多结帐文档http://nodejs.org/api/crypto.html

如果你知道如何从OpenSSL中得到你想要的,我认为使用Node的child_process运行OpenSSL是完全合理的。

 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(); }); 

child_process路由是一个可怕的,不可扩展的解决scheme。 远离。

我select使用密钥对来代替。

干杯

我没有使用它,但这可能是有用的:

http://ox.no/posts/diffie-hellman-support-in-node-js

文档严重缺乏(没有我能find的例子)。

你可以使用这个rsa-json模块 。 它只是产生了一个openssl进程,所以它依赖于操作系统(它在windows上默认不起作用)。