Node.js 使 rsa 加密的正确方法? [英] Node.js correct way to make rsa encrypt?
问题描述
我正在尝试为 make soap 请求创建一个 WS.在消息正文中有一个包含加密文本的字段.我有公钥来加密文本,但我获得的唯一结果是无法识别文本.我使用节点的加密模块进行请求并且文本被加密,但我不知道为什么没有正确加密.
i'm trying to create a WS for make soap request. In the body of the message there is a field that contains an encrypted text. I have the public key to encrypt the text but the only result that i obtain is that the text is not recognized. I use crypto module of node for making request and the text is crypted but i don't know why is not correclty encrypted.
Ps 我用 openssl_public_encrypt 函数在 php 上做了同样的事情并且工作.但我必须在 node.js 中完成.
Ps i made the same thing on php with openssl_public_encrypt function and working. But i have to do it in node.js.
有什么想法或建议吗?openssl_public_encrypt 与 crypto.publicEncrypt 函数有什么不同?
Any idea or suggestion? What is different openssl_public_encrypt from crypto.publicEncrypt function?
这里是 node.js 中的加密部分:
Here is the encrypt part in node.js:
var crypto = require("crypto");
var fs = require('fs');
fs.readFile("./certificate.pem", 'utf8', function (err, data) {
var bufferToEncrypt = new Buffer("textToEncrypt");
var encrypted = crypto.publicEncrypt({"key":data, padding:crypto.RSA_NO_PADDING}, bufferToEncrypt).toString("base64");
console.log(encrypted); // length 128
}
在 php 中同样的事情:
The same thing in php:
<?php
$publicKey = "./certificate.pem";
$plaintext = "textToEncrypt";
openssl_public_encrypt($plaintext, $encrypted, $publicKey);
echo base64_encode($encrypted); //encrypted string length 128
?>
我没有解密文本的私钥,我只有公钥.
I don't have the private key for decrypting the text, i only have the public key.
还要注意加密文本的长度(base64)在php和node.js中是一样的.
Also notice that the length of the encrypted text (in base64) is the same in php and in node.js.
推荐答案
我想填充是你的问题.在 node.js 中,您指定 padding:crypto.RSA_NO_PADDING
.在查找 openssl_public_encrypt()
的文档时,它说它默认使用 OPENSSL_PKCS1_PADDING
.请尝试以下操作:
I guess the padding is your problem. In node.js you specify padding:crypto.RSA_NO_PADDING
. When looking up the doc of openssl_public_encrypt()
it says that it uses OPENSSL_PKCS1_PADDING
by default. Try the following:
var constants = require("constants");
var encrypted = crypto.publicEncrypt({"key":data,
padding:constants.RSA_PKCS1_PADDING}, bufferToEncrypt).toString("base64");
我准备了一个在线演示:
I have prepared an online demo:
- 使用 node.js 加密
- 复制结果字符串
- 并将其粘贴到 PHP 解密示例 上的
$encrypted_encoded
<小时>
建议:根据经验,不要对实际消息使用非对称加密.改用它来保护对称密钥.但是,您的用例可能是有效的,我只是想在每次有人谈论 RSA 加密时说明这一点.
Advise: As a rule of thumb, don't use asymmetric encryption for actual messages. Use it to protect a symmetric key instead. However, your use case might be valid, I just want to state this every time someone talks RSA encryption.
这篇关于Node.js 使 rsa 加密的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!