rzcoder / node-rsa

Node.js RSA library
1.39k stars 205 forks source link

hex encrypted string cannot be decrypted #222

Closed TheSlimvReal closed 1 year ago

TheSlimvReal commented 2 years ago

I am currently trying to encrypt a string in hex because I need to use it as a query param. With base64 encoding I would have to url-encode it first due to the special characters in base64.

I am trying the following code:

const rsa = new NodeRSA({ b: 512 });
const text = 'Hello World!';
const encrypted = rsa.encrypt(text, 'hex');
console.log('encrypted', encrypted);
const decrypted = rsa.decrypt(encrypted, 'utf8');
console.log('decrypted', decrypted);

However, it always throws me the error:

Error during decryption (probably incorrect key). Original error: Error: Incorrect data or key

Any idea why this is happening?

In the source code I found the following line (nodeRSA.js line 292) which looks like NodeRSA always expects a base64 string?

buffer = _.isString(buffer) ? Buffer.from(buffer, 'base64') : buffer;

Thanks for any advice or possible solutions!

doublekai commented 1 year ago

hello, unfortunately I came across this problem, please have you solved it?

TheSlimvReal commented 1 year ago

@doublekai yes, after some digging around I came across this solution. The hex string needs to be parsed to base64 first:

const rsa = new NodeRSA();
const text = "my message";
const encrypted = rsa.encrypt(text, 'hex');
console.log("encrypted", encrypted);
const base64Encrypted = Buffer.from(encrypted, 'hex').toString('base64');
const decrypted rsa.decrypt(base64Encrypted, 'utf8');
console.log("decrypted", decrypted);