search

Home  >  Q&A  >  body text

node.js - RSA算法使用公钥加密,前端和后端得到的密文不一致

1.鄙人在做一个安全登录的实验时,接触到jQuery插件jCryption,版本为3.1.0。密钥对以pem文件格式存放在服务器,客户端请求公钥,则读取公钥文件返回给客户端。客户端用公钥加密之后将信息交给服务器,但是服务器一直解密错误(node.js用的类库为node-rsa)

2.后来仔细检查发现前端加密得到的密文与后端得到的密文不一致
如图:
这是前端打印的公钥
-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC0hFaQcFU481wyhy5JXOv/cgOp
2xQXISjc31cfPk/Ba33j2DayrRr0lWapqIBUPPVECV4wz/S1Gq4NIPDJzIpwSkGG
+XCDccJmtbyd7UhWlqphm8Lsc4AKa28Y7pcxWs6t78fxHHBb06+N7PlNhdWu8sPj
ZLdoCxdIS9WWYuB1EQIDAQAB
-----END PUBLIC KEY-----

这是前端加密的数据
9e5040bed296c4810aa8f8f96b00b9370e3ca171c66942c358441d56d29125bf
这是前端得到的密文
jlKIiz3cW2ethkQauow89QcRnKaac8+r4dwdvYYAIqbbQlSz0bJV7WTx69Xvu/fZ8p9yolg94Lb56nfqwX0yyx4E7at+6YwHL1HxEAiM+zqL+U9gZZGZ04KmH/zScdFHdtnQixe2FwtPa6TFDK5XgUM7C7rsNrvToIipPRp+1qI=

而后端从pem文件中读取公钥加密同样的数据,得到的密文是:
FZRzdEbMeaJruhJWYT1dxNZ+Ho7QVxcic/XGQcqfgwZuQdhKqyxPQskg/ddbti52TztV21AH9MuQBDk7vVpfD/3N2ZsqCib0s0XGfPkN8LYoJ4l4lx9JigGYjLtRk34WxV7AZPVsJ1r9TCwYYitQCHQAT6PW5+O6rpPlVsYQ2yY=

以如下形式使用私钥:

得到的密文也不相同.

将上图中的私钥部分的换行符全部去掉得到的密文任然不相同。

我想问的是jCryption这个插件将字符串设置为公钥的时候怎么操作的,怎样才能使得前端和后端加密得到的密文一致,可以互相加解密呢?

请各位大神指教,困扰好几天了,不胜感谢。

怪我咯怪我咯2777 days ago1583

reply all(3)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:46:21

    Although I can’t help you with jCryption, we found a librsa from the Internet during development, and the probably annotation was

    // Copyright (c) 2005  Tom Wu
    // All Rights Reserved.
    // See "LICENSE" for details.
    
    // Basic JavaScript BN library - subset useful for RSA encryption.
    
    // Bits per digit

    Then export JSEncrypt

    This thing had no problem connecting with php, java, and ios. When using it, you directly provide the public key and the string to be encrypted, and there is no need to provide these parameters to the module

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:46:21

    Let me answer it myself

    In the node-rsa module, pkcs1_oaep is used by default for encryption and decryption, while pkcs1 is used by default for encryption and decryption in js. There is a function provided in node-rsa to modify this option

    var rsakey = new NodeRSA();
    rsakey.setOptions({encryptionScheme: 'pkcs1'});//就是增加这一行代码。
    

    Reference: http://stackoverflow.com/questions/33837617/node-rsa-errors-when-trying-to-decrypt-message-with-private-key

    reply
    0
  • 大家讲道理

    大家讲道理2017-04-17 13:46:21

    If you make sure that your plaintext is the same and the public key is the same, the possible reason is that the padding methods used in your front-end and back-end encryption are different.

    reply
    0
  • Cancelreply