Error in decoding with RSA padding check PKCS1 OAEP MGF1 routines in JSencrypt for Node.js Crypto

I've been utilizing the NodeJS Crypto module for encryption and decryption with RSA on the backend, while using JSencrypt for frontend RSA operations.

The problem arises when I attempt to encrypt data on the frontend using a public key, resulting in an error being thrown by the backend (Note: I'm implementing this in NuxtJS and utilizing the import function).

const { JSEncrypt } = await import('jsencrypt')
const rsa = new JSEncrypt({ default_key_size: 1024 })
rsa.setPublicKey(store.state.publicKey)
const xKey = rsa.encrypt(store.state.ticket)

Subsequently, when trying to decrypt the encoded data on the backend, the following error is generated:

Error: error:04099079:rsa routines:RSA_padding_check_PKCS1_OAEP_mgf1:oaep decoding error

Showcased below is the backend code employed for RSA decryption utilizing the private key:

const privateKey = fs.readFileSync('RSA_private.key', { encoding: 'utf8' })

exports.RSAdecrypt = async (data) => {
    const buffer = Buffer.from(data, "base64")
    const decrypted = crypto.privateDecrypt(privateKey, buffer)
    return decrypted.toString('utf8')
}

Answer №1

If users continue to encounter issues, I came across a different error message while attempting the same process as outlined in the solution provided. To address this, you can modify the code to pass the crypto constant without padding:

crypto.privateDecrypt(
      {
        key: this.privateKey,
        passphrase: '<passPhrase>',
        padding: crypto.constants.RSA_NO_PADDING, // <-- Give this a try
      }, 
      Buffer.from(encryptedText, 'base64')).toString('utf8');

Answer №2

I stumbled upon a solution. While browsing through this article, I discovered that JSencrypt utilizes pkcs1 padding as the default. As a result, I decided to modify my decryptor code to incorporate pkcs1. Typically, Node crypto defaults to using pkcs1_oaep.

Below is the snippet of code for the decryptor.

exports.RSAdecrypt = async (data) => {
    const buffer = Buffer.from(data, "base64")
    const decrypted = crypto.privateDecrypt({ key: privateKey, padding: crypto.constants.RSA_PKCS1_PADDING }, buffer)
    return decrypted.toString('utf8')
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the proper way to gracefully stop a koajs server?

Is there a way to gracefully stop koajs like I've seen for expressjs? I also need to disconnect database connections during the process. Specifically, I have a mongoose database connection and 2 oracle db connections (https://github.com/oracle/node- ...

I am having an issue where my Express/Angular application is not redirecting properly after

Currently in my Express setup: var router = express.Router(); router.get('/auth/*', function (req, res, next) { next(); }) app.use(router); app.all('/*', function(req, res) { res.sendfile('index.html', { root: __dirname ...

The error message that is popping up on Windows when running `npm start` is

Hey there! I'm having an issue with my Windows 10 installation and Mean. After installing express, I tried to start npm using the command "npm start" but encountered the following error: C:\>npm start npm ERR! Windows_NT 6.3.9600 npm ERR! arg ...

What is the best approach for implementing an Express Form that allows for image uploads to S3, with the subsequent saving of the S3 URL to a MongoDB field?

I am facing a roadblock at the moment. I have a form that is used for writing blog posts and I was previously using multer to upload images to mongodb as a datastream. However, due to scalability issues, I decided to switch to uploading images to S3 but I& ...

Guide to creating a dynamic node package that updates itself autonomously

We currently have a node_module known as bookiza, which serves as a command line tool that users install globally and utilize to create and publish books online. While we generally adhere to semver conventions for versioning, I anticipate stricter adherenc ...

What is the best way to extract a value from a JSON object?

I am having trouble deleting data from both the table and database using multiple select. When I try to delete, it only removes the first row that is selected. To get the necessary ID for the WHERE condition in my SQL query, I used Firebug and found this P ...

What is the necessity of verifying that the password remains unchanged once the JWT has been generated?

I'm having trouble understanding why it's necessary to check if the password has been changed after issuing the JWT. I have a code snippet here that handles user authorization, but the reason for this specific check is unclear to me. Can someone ...

I need to know the appropriate version of Node.js to use for installing the mobile-first development kit and migration assistance

My server version is mobile-first 8.0.0.00-20180220-083852 I downloaded the cli and migration assistance tool, but I keep encountering this error: npm ERR! node v6.9.3 npm ERR! npm v3.10.10 npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! sysca ...

Struggling to locate a suitable mock server that can deliver JSON responses for a specific URL that has been predetermined

I have encountered a challenge in my frontend app development using vue.js. I need to find a mock backend server (without mocking it on the front end). My app is capable of making HTTP requests, specifically GET and PATCH are the methods of interest. I am ...

Issue encountered during npm installation command

Recently diving into nodejs and experimenting with the Visual Studio Code editor. Encountering difficulties in installing packages, with an error message indicating a possible issue related to the proxy. Despite attempting various solutions found online ( ...

Completing a Promise without invoking the 'then' method

As I work on developing a small API for the NPM module Poolio, one common dilemma arises regarding error-first callbacks and promises. The challenge lies in how to cater to both types of asynchronous functions while maintaining consistency in APIs and retu ...

Error in Firebase cloud functions: The reference to the child is invalid. Please check the path provided as the first argument

I'm currently working on implementing push notifications by following this tutorial: https://www.youtube.com/watch?v=z27IroVNFLI Although the tutorial is a bit dated, there aren't many viable alternatives for Firebase web apps. When my cloud fu ...

Executing a task utilizing a designated child process in Node.js

Although I'm familiar with forking a child process, my specific requirement involves using this child process to perform certain tasks. For instance, when clicking a button, I need the child process to handle processing form data for saving. This hand ...

My server keeps crashing due to an Express.js API call

I'm completely new to express.js and API calls, and I'm stuck trying to figure out why my server keeps crashing. It works fine the first time, rendering the page successfully, but then crashes with the error: TypeError: Cannot read property &apo ...

Now that connect no longer utilizes the parseCookie method, what is the alternative method for accessing session data in express?

There are numerous examples in node.js and express showcasing how to access session data. Exploring Node.js and Socket.io Express and Socket.io Integration Understanding Socket.io and Session Management Upon visiting the third link, which leads to Stac ...

Is it necessary for me to specify models in sequelizejs?

After spending some time experimenting with expressjs, I am now looking to connect to a mysql database. I typically use MySQL Workbench to create my database tables because of the ForeignKeys feature it offers. I haven't yet discovered how to replicat ...

Connecting HTML POST to MongoDB using NodeJS

I am in the process of developing a blog application using Node, Express, and MongoDB. My goal is to create an HTML form that will allow users to submit new blog posts directly to the database. While I have successfully implemented GET and POST requests us ...

"Uh-oh, looks like we've hit a snag: the module '../time/convert' is nowhere to be found. This issue seems to be

I recently set up a new Angular project on Linux, committed it to Git, and then cloned it onto Windows. Using Bower and NPM, I successfully loaded everything except for one error that only occurs on Windows. Upon performing a recursive grep search for ../ ...

Nock does not capture the requests - Error: Failed to resolve address ENOTFOUND

Let me provide an overview of the structure in place. Jest is utilized for executing the testing process. Within my jest.config.json file, I incorporate the following line: "globalSetup": "<rootDir>/__tests__/setup.js", Inside setup.js, you will ...

Establish the designated callback URL for iOS applications within an Express framework

My current project involves an Express app that has a feature allowing users to sign in with Google using passport-google-oauth20. The callback route for this functionality is set as: https://(hosturl)/auth/google/redirect. I am currently facing an issue ...