javascriptnode.jsencryptionrsajsencrypt

Decrypting RSA with JavaScript


I am writing a web app which receives an RSA encrypted response from a server. It needs to decrypt this file.

So far, I have tried to use JSEncrypt to decrypt the file on the frontend. The issue seems to be that the backend is not encrypting the file properly. If I put both the private and public key on the frontend, I can encrypt and decrypt successfully. The issue seems to be the way that I am encrypting the response. When I read in the file in nodeJS and encrypt the file with the following code:

fs.readFile("rsaPublicKey", "utf8", (err, data) => {
  if (err) throw err;

  pubKey = data;
});
encryptedMessage = crypto.publicEncrypt(
  {
    key: pubKey,
    padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
    oaepHash: "sha256",
  },
  Buffer.from(message)
);

res.send({"response": encryptedMessage.toString("base64")});

The message is bigger than the same message being encrypted with JSEncrypt.

Node.JS message: WLptALzMMws/Qj8qzeYkQ1NyRknoBGX0+oHmtzd0Cwl/RmWnwt6wSJ1qdbk5GMPcEML5iqCISqTfPTSEC6M37KIJAgGLViPENKcvonT7qQbMsn0yftFMl9grn1oLQz567t3lWpdyuCa99xqG+tGsAAOK84HHCW+nprSH6+7olysTnSzzZWvvBl6VGTpmwtoBEGOnZ5C/XLwiW7b2UuzHsksIA1s55OkJMOOUA6neZiJIzHsJSHZGgigKvKwYNQbjhmEBbdNVSvCPIE/d9dpTtWNABcnQX7SCA6/sTZH/f0OnGGXOyYabhq84fdw/WwpouUBWsRQLQYJgKy3EqY/y/w==

JSEncrypt message: Sq9KQyp7KDqy1CBFRLtXm4ZAdxidgUNlp0d6X6xm3m+aBXKv4H7DVu0O40EMWeSWl3dQcBBC/oguJsoAz/GY//77ElIPIRuvPK4YIWPNq2fjoIgIs3Ew4I5TKAP4rph//NSlDLPc4ppXQjj/YO2238EHney9Wxxa9EZzE/p48arkxuEjB0gakWyVgTlF8x6H7LGsD4epS7RWJ0ua1kG1J6ZuMB82qBvq2MugLEuQamAfml4LtwWYFTJ/dIcAqVqrtHe6/F2oNGwXsE2GDEeZcFr4vTkejCs5dFcbbcgg/KVnROdGQHJlDGl0uUBy/2UNml3cT3FocjXkPGJa0zu3/g==

Is there any way to try and get this to work?


Solution

  • It turns out JSEncrypt does not support the padding I was using in the backend. I changed the padding in the backend to crypto.constants.RSA_PKCS1_PADDING as shown by Topaco in the comments. Another possible option would be to use https://github.com/michaeldisaro/JSEncrypt and use OAEP padding again.