Unable to correctly encrypt data using RSA/ECB/PKCS1 in nodejs

2.8k Views Asked by At

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.

3

There are 3 best solutions below

0
Woodstock On

You're using the wrong key to decrypt.

You should use the private key.

key.decrypt(buffer, [encoding]);

Not the public key as you currently are:

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

RSA generally flows as, encrypt with public, decrypt with private.

0
Yonas Alem On

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

and this how You decrypt it let readPrivateKey = fs.readFileSync("./keys/private_key.txt", "utf-8"); let decrypted = privateDecrypt(readPrivateKey, decryptBuffer);

this is what solve the problem which the the encoding scheme for both encryption and decryption should be the same.

0
KamiSama On

If you are using the public key to encrypt, you can't use it for decryption, due to how asymmetric encryption works.

The crypto.privateDecrypt() is used for decrypting the given data content by using a private key passed in the parameter that was previously encrypted using the corresponding public key with the crypto.publicEncrypt() method.

Also see tutorialspoint - crypto.privateDecrypt() Method in Node.js