【问题标题】:Unable to correctly encrypt data using RSA/ECB/PKCS1 in nodejs无法在 nodejs 中使用 RSA/ECB/PKCS1 正确加密数据
【发布时间】:2021-04-06 23:13:07
【问题描述】:

我使用node-rsa包加密数据如下

const crypto = require('crypto')
const NodeRSA = require('node-rsa')
const path = require("path")
const fs = require("fs")

const absolutePath = path.resolve('./public_key.pem')
const publicKey = fs.readFileSync(absolutePath, "utf8")

var key = new NodeRSA();
key.importKey(publicKey, 'pkcs8-public');
key.setOptions({environment: 'node', encryptionScheme: 'pkcs1'});
const result = key.encrypt('{"message": "hello"}', 'base64')

但是现在当我尝试解密结果如下:

key.decryptPublic(result, 'utf-8')

我收到以下错误消息:

错误:解密过程中出错(可能是不正确的密钥)。原来的 错误:错误:错误:0407008A:rsa 例程:RSA_padding_check_PKCS1_type_1:无效填充 在 NodeRSA.module.exports.NodeRSA.$$decryptKey (/home/runner/node_modules/node-rsa/src/NodeRSA.js:301:19) 在 NodeRSA.module.exports.NodeRSA.decryptPublic (/home/runner/node_modules/node-rsa/src/NodeRSA.js:267:21) 在 evalmachine.:16:17 在 Script.runInContext (vm.js:133:20) 在 Object.runInContext (vm.js:311:6) 在评估 (/run_dir/repl.js:133:14) 在读取流。 (/run_dir/repl.js:116:5) 在 ReadStream.emit (events.js:198:13) 在 addChunk (_stream_readable.js:288:12) 在 readableAddChunk (_stream_readable.js:269:11)

我该如何解决这个问题?

谢谢。

【问题讨论】:

标签: javascript node.js cryptography node-rsa


【解决方案1】:

您使用了错误的密钥来解密。

您应该使用私钥。

key.decrypt(buffer, [encoding]);

不是你现在的公钥:

key.decryptPublic(buffer, [encoding]); // use public key for decryption

RSA 通常是这样流动的,用 public 加密,用 private 解密。

【讨论】:

    【解决方案2】:

    let encryptedText = encrypted.toString("base64");

    这就是你解密它的方式 让 readPrivateKey = fs.readFileSync("./keys/private_key.txt", "utf-8"); 让解密 = privateDecrypt(readPrivateKey, decryptBuffer);

    这就是解决加密和解密的编码方案应该相同的问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-14
      • 2019-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多