drj58429 2016-01-22 18:40
浏览 138
已采纳

Node.js正确的方法使rsa加密?

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 i made the same thing on php with openssl_public_encrypt function and working. But i have to do it in node.js.

Any idea or suggestion? What is different openssl_public_encrypt from crypto.publicEncrypt function?

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
}

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.

Also notice that the length of the encrypted text (in base64) is the same in php and in node.js.

  • 写回答

1条回答 默认 最新

  • drbmhd9583 2016-01-22 21:31
    关注

    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:

    1. Encrypt using node.js
    2. copy the resulting string
    3. and paste it to $encrypted_encoded on PHP decryption example

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 echarts动画效果失效的问题。官网下载的例子。
  • ¥60 许可证msc licensing软件报错显示已有相同版本软件,但是下一步显示无法读取日志目录。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加