简体   繁体   中英

Node-rsa Encrypting Public key from the pem file and trying to decrypt, but getting following error. (probably incorrect key) NODEJS

Error: Error during decryption (probably incorrect key). Original error: Error: This is not private key

Here is my nodejs code. I am using node-rsa.

  const keyData = fs
    .readFileSync("./docs/PublicKey/XXX_sandbox.pem")
    .toString();
  const NodeRSA = require("node-rsa");
  var key = new NodeRSA();
  key.importKey(keyData, "pkcs8-public");
  const encrypted = key.encrypt("Test@1234", "base64");
  console.log("encrypted: ", encrypted);

Here is my pem file:

-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArxd93uLDs8HTPqcSPpxZ
rf0Dc29r3iPp0a8filjAyeX4RAH6lWm9qFt26CcE8ESYtmo1sVtswvs7VH4Bjg/F
DlRpd+MnAlXuxChij8/vjyAwE71ucMrmZhxM8rOSfPML8fniZ8trr3I4R2o4xWh6
no/xTUtZ02/yUEXbphw3DEuefzHEQnEF+quGji9pvGnPO6Krmnri9H4WPY0ysPQQ
Qd82bUZCk9XdhSZcW/am8wBulYokITRMVHlbRXqu1pOFmQMO5oSpyZU3pXbsx+Ox
IOc4EDX0WMa9aH4+snt18WAXVGwF2B4fmBk7AtmkFzrTmbpmyVqA3KO2IjzMZPw0
hQIDAQAB
-----END PUBLIC KEY-----

I solved my problem by setting encrytionScheme to "pkcs1". Find the code below. Use key.setOptions in node-rsa.

var NodeRSA = require("node-rsa");

var key = new NodeRSA();

const keyData =
    "-----BEGIN PUBLIC KEY-----\n" +
    "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEArxd93uLDs8HTPqcSPpxZ\n" +
    "rf0Dc29r3iPp0a8filjAyeX4RAH6lWm9qFt24CcE8ESYtmo1sVtswvs7VH4Bjg/F\n" +
    "DlRpd+MnAlXuxChij8/vjyAwE71ucMrmZhxM8rOSfPML8fniZ8trr3I4R2o4xWh6\n" +
    "no/xTUtZ02/yUEXbphw3DEu9fzHEQnEF+quGji9pvGnPO6Krmnri9H4WPY0ysPQQ\n" +
    "Qd82bUZCk9XdhSZcW/am8wBulYokITRMVHlbRXqu1pOFmQMO5oSpyZU3pXbsx+Ox\n" +
    "IOc4EDX0WMa9aH4+snt18WAXVGwF2B4fmBk7AtmkFzrTmbpmyVqA3KO2IjzMZPw0\n" +
    "hQIDAQAB\n" +
    "-----END PUBLIC KEY-----";

//setOptions ecryptionScheme is default to pkcs1_oaep by setting this to pkcs1. I could able to solve my problem

  key.setOptions({
    encryptionScheme: "pkcs1"
  });

  key.importKey(keyData, "pkcs8-public");
  const encrypted = key.encrypt("Test@1234", "base64");
  res.send(encrypted);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM