在 node.js 中使用公钥加密数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8750780/
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
Encrypting data with Public Key in node.js
提问by Clint
I need to encrypt a string using a public key (pem file), and then sign it using a private key (also a pem).
我需要使用公钥(pem 文件)加密字符串,然后使用私钥(也是 pem)对其进行签名。
I am loading the pem files fine:
我正在加载 pem 文件:
publicCert = fs.readFileSync(publicCertFile).toString();
but after hours of scouring google I can't seem to find a way to encrypt data using the public key. In php I simply call openssl_public_encrypt, but I don't see any corresponding function in node or in any modules.
但是经过数小时的搜索谷歌,我似乎无法找到一种使用公钥加密数据的方法。在 php 中,我只是调用 openssl_public_encrypt,但在节点或任何模块中我没有看到任何相应的函数。
If anyone has any suggestions, let me know.
如果有人有任何建议,请告诉我。
回答by Jacob McKay
No library necessary friends,
没有图书馆必备的朋友,
Enter crypto
输入密码
Here's a janky little module you could use to encrypt/decrypt strings with RSA keys:
这是一个可用于使用 RSA 密钥加密/解密字符串的简陋小模块:
var crypto = require("crypto");
var path = require("path");
var fs = require("fs");
var encryptStringWithRsaPublicKey = function(toEncrypt, relativeOrAbsolutePathToPublicKey) {
var absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey);
var publicKey = fs.readFileSync(absolutePath, "utf8");
var buffer = Buffer.from(toEncrypt);
var encrypted = crypto.publicEncrypt(publicKey, buffer);
return encrypted.toString("base64");
};
var decryptStringWithRsaPrivateKey = function(toDecrypt, relativeOrAbsolutePathtoPrivateKey) {
var absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey);
var privateKey = fs.readFileSync(absolutePath, "utf8");
var buffer = Buffer.from(toDecrypt, "base64");
var decrypted = crypto.privateDecrypt(privateKey, buffer);
return decrypted.toString("utf8");
};
module.exports = {
encryptStringWithRsaPublicKey: encryptStringWithRsaPublicKey,
decryptStringWithRsaPrivateKey: decryptStringWithRsaPrivateKey
}
I would recommend not using synchronous fs methods where possible, and you could use Promises to make this better, but for simple use cases this is the approach that I have seen work and would take
我建议在可能的情况下不要使用同步 fs 方法,您可以使用 Promises 来改进它,但对于简单的用例,这是我见过的可行方法并且会采用
回答by BrunoLM
I tested this in Node 10, you can use encrypt/decrypt functions (small changes on Jacob's answer)
我在 Node 10 中对此进行了测试,您可以使用加密/解密函数(Jacob 的答案的小改动)
const crypto = require('crypto')
const path = require('path')
const fs = require('fs')
function encrypt(toEncrypt, relativeOrAbsolutePathToPublicKey) {
const absolutePath = path.resolve(relativeOrAbsolutePathToPublicKey)
const publicKey = fs.readFileSync(absolutePath, 'utf8')
const buffer = Buffer.from(toEncrypt, 'utf8')
const encrypted = crypto.publicEncrypt(publicKey, buffer)
return encrypted.toString('base64')
}
function decrypt(toDecrypt, relativeOrAbsolutePathtoPrivateKey) {
const absolutePath = path.resolve(relativeOrAbsolutePathtoPrivateKey)
const privateKey = fs.readFileSync(absolutePath, 'utf8')
const buffer = Buffer.from(toDecrypt, 'base64')
const decrypted = crypto.privateDecrypt(
{
key: privateKey.toString(),
passphrase: '',
},
buffer,
)
return decrypted.toString('utf8')
}
const enc = encrypt('hello', `public.pem`)
console.log('enc', enc)
const dec = decrypt(enc, `private.pem`)
console.log('dec', dec)
For the keys you can generate them with
对于密钥,您可以使用
const { writeFileSync } = require('fs')
const { generateKeyPairSync } = require('crypto')
function generateKeys() {
const { privateKey, publicKey } = generateKeyPairSync('rsa', {
modulusLength: 4096,
publicKeyEncoding: {
type: 'pkcs1',
format: 'pem',
},
privateKeyEncoding: {
type: 'pkcs1',
format: 'pem',
cipher: 'aes-256-cbc',
passphrase: '',
},
})
writeFileSync('private.pem', privateKey)
writeFileSync('public.pem', publicKey)
}
回答by Louie Miranda
The updated public/private decrypt and encryption module is URSA. node-rsa module is outdated.
更新的公/私解密和加密模块是 URSA。node-rsa 模块已过时。
This Node module provides a fairly complete set of wrappers for the RSA public/private key crypto functionality of OpenSSL.
该 Node 模块为 OpenSSL 的 RSA 公钥/私钥加密功能提供了一组相当完整的包装器。
npm install ursa
npm 安装 ursa
回答by Peter Lyons
How about this node-rsa module? Here's a link to the test.js file that demonstrates usage.
这个node-rsa 模块怎么样?这是演示用法的test.js 文件的链接。
回答by B T
TL;DR: Ursa is your best bet. Its really funky that this doesn't come standard with node crypto.
TL;DR:Ursa 是你最好的选择。这真的很时髦,这不是节点加密的标准。
Every other solutions I found either doesn't work in windows or aren't actually encryption libraries. Ursa, recommended by Louie, looks like the best bet. If you don't care about windows, you're even more golden. Note on Ursa, I had to install Open SSL along with something called "Visual C++ 2008 Redistributables" in order to get the npm install to work. Get that junk here: http://slproweb.com/products/Win32OpenSSL.html
我发现的所有其他解决方案要么在 Windows 中不起作用,要么实际上不是加密库。Louie 推荐的 Ursa 看起来是最好的选择。如果你不在乎窗户,你就更金了。请注意 Ursa,我必须安装 Open SSL 以及名为“Visual C++ 2008 Redistributables”的东西,以便 npm install 工作。在此处获取垃圾:http: //slproweb.com/products/Win32OpenSSL.html
The breakdown:
细分:
- Annoying additional manual installation steps for windows
- https://github.com/Obvious/ursa- probably the best of the lot
- Not compatible with windows
- https://npmjs.org/package/rsautl- says BADPLATFORM
- https://github.com/katyo/node-rsa- node-waf isn't available on windows
- https://github.com/paspao/simple_rsa_encrypt- unistd.h isn't on windows
- https://npmjs.org/package/pripub- large amounts of linker errors, also not on github
- Not encryption libraries
- https://github.com/substack/secure-peer
- https://github.com/substack/rsa-json- just generates keys, doesn't use them
- https://github.com/substack/rsa-unpack- just unpacks PEM strings
- 烦人的 Windows 额外手动安装步骤
- https://github.com/Obvious/ursa- 可能是最好的
- 与windows不兼容
- https://npmjs.org/package/rsautl- 说 BADPLATFORM
- https://github.com/katyo/node-rsa- node-waf 在 Windows 上不可用
- https://github.com/paspao/simple_rsa_encrypt- unistd.h 不在 Windows 上
- https://npmjs.org/package/pripub- 大量链接器错误,也没有在 github 上
- 不是加密库
This is literally all I could find.
这就是我能找到的所有内容。
回答by Etienne
This is not supported natively by node version v0.11.13 or below but it seems that next version of node ( a.k.a v0.12) will support this.
节点版本 v0.11.13 或更低版本本身不支持此功能,但似乎下一版本的节点(又名 v0.12)将支持此功能。
Here is the clue: https://github.com/joyent/node/blob/v0.12/lib/crypto.js#L358
这是线索:https: //github.com/joyent/node/blob/v0.12/lib/crypto.js#L358
see crypto.publicEncryptand crypto.privateDecrypt
看到 crypto.publicEncrypt和crypto.privateDecrypt
Here is the future documentation for this https://github.com/joyent/node/blob/7c0419730b237dbfa0ec4e6fb33a99ff01825a8f/doc/api/crypto.markdown#cryptopublicencryptpublic_key-buffer
这是此https://github.com/joyent/node/blob/7c0419730b237dbfa0ec4e6fb33a99ff01825a8f/doc/api/crypto.markdown#cryptopublicencryptpublic_key-buffer的未来文档

