Im using the node-rsa package for encrypting data as follows
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')
But now when i try to decrypt the result as follows:
key.decryptPublic(result, 'utf-8')
I get the following error message:
Error: Error during decryption (probably incorrect key). Original error: Error: error:0407008A:rsa routines:RSA_padding_check_PKCS1_type_1:invalid padding at NodeRSA.module.exports.NodeRSA.$$decryptKey (/home/runner/node_modules/node-rsa/src/NodeRSA.js:301:19) at NodeRSA.module.exports.NodeRSA.decryptPublic (/home/runner/node_modules/node-rsa/src/NodeRSA.js:267:21) at evalmachine.:16:17 at Script.runInContext (vm.js:133:20) at Object.runInContext (vm.js:311:6) at evaluate (/run_dir/repl.js:133:14) at ReadStream. (/run_dir/repl.js:116:5) at ReadStream.emit (events.js:198:13) at addChunk (_stream_readable.js:288:12) at readableAddChunk (_stream_readable.js:269:11)
How can i fix this ?
Thanks.
You're using the wrong key to decrypt.
You should use the private key.
Not the public key as you currently are:
RSA generally flows as, encrypt with public, decrypt with private.