如何使用 Node.js 加密创建一对私钥/公钥?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8520973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a pair private/public keys using Node.js crypto?
提问by Dail
I have to generate two keys (private and public) to encrypt a text with the public and let the user with the private key decrypt the text.
我必须生成两个密钥(私有和公共)来用公共加密文本,并让拥有私有密钥的用户解密文本。
Is it possible with the module Crypto?
Crypto 模块可以吗?
回答by Nelson Owalo
nodejs v10.12 now supports this natively with crypto.generateKeyPair
nodejs v10.12 现在通过crypto.generateKeyPair原生支持这个
const { generateKeyPair } = require('crypto');
generateKeyPair('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: 'top secret'
}
}, (err, publicKey, privateKey) => {
// Handle errors and use the generated key pair.
});
回答by Aks
Use the crypto module from npm to generate KeyPair.
使用 npm 中的 crypto 模块生成 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'));
Above is a example snippet. To know more checkout documentation http://nodejs.org/api/crypto.html
上面是一个示例片段。要了解更多结帐文档http://nodejs.org/api/crypto.html
回答by fadedbee
The following code works, but I'm not a professional cryptographer, so some comments here would be useful.
以下代码有效,但我不是专业的密码学家,所以这里的一些评论会很有用。
I've used the ursa RSA module, instead of crypto.
我使用了 ursa RSA 模块,而不是加密。
I am concerned that if similar data were encrypted directly, without a pass of AES or similar, then it might be trivial to break this. Comments please...
我担心如果类似的数据是直接加密的,而没有通过 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);
After some further investigation http://en.wikipedia.org/w/index.php?title=RSA_%28cryptosystem%29§ion=12#Attacks_against_plain_RSAit looks like ursa already does padding.
经过一些进一步的调查http://en.wikipedia.org/w/index.php?title=RSA_%28cryptosystem%29§ion=12#Attacks_against_plain_RSA看起来 ursa 已经做了填充。
回答by kgilpin
If you know how to get what you want from OpenSSL, I think it's perfectly reasonable to run OpenSSL using Node's child_process.
如果您知道如何从 OpenSSL 获得您想要的东西,我认为使用 Node 的child_process.
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();
});
回答by Guido
You can use this rsa-json module. It just spawns a openssl process, so it is pretty dependent on the OS (it does not work by default on windows).
你可以使用这个 rsa-json 模块。它只是产生一个 openssl 进程,所以它非常依赖于操作系统(默认情况下它在 Windows 上不起作用)。
回答by redditmerc
回答by Steve Campbell
I have not used it, but this may be useful:
我没有使用过它,但这可能很有用:
http://ox.no/posts/diffie-hellman-support-in-node-js
http://ox.no/posts/diffie-hellman-support-in-node-js
Documentation is severely lacking on this (no examples that I could find).
严重缺乏这方面的文档(我找不到示例)。
回答by Nats_Ayala
const crypto = require('crypto');
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});

