如何使用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);
使用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使用密钥对来代替。
干杯
你可以使用这个rsa-json模块 。 它只是产生了一个openssl进程,所以它依赖于操作系统(它在windows上默认不起作用)。
- mongodb:encryption字段上的唯一索引
- 在PHP 7encryption解密在节点JS
- 使用Node.jsencryption模块进行encryption并使用Java解密(在Android应用程序中)
- 生成iv时出现crypto.createDecipheriv错误
- Node.JS和PHP AES-128-EBC数据encryption
- CryptoSwiftencryption的数据与Node.js不同
- 将AES Java解密代码移植到Node.js
- 从JavaScript创build一个PEM文件看起来不同于Java导致签名validation失败
- 使用ruby解密encryption数据