Unveil the key using RSA Public Key decryption in JavaScript

Hey there to the StackOverFlow Community!

Let's talk decrypting a hash message with the RSA Public Key. When logging in to my application, the backend service provides me with an RSA Public Key which I save for future message decryption purposes. The backend then sends me an encrypted payload using the private key and I need to decrypt it using the stored public key.

I rely on the jsencrypt library for this encryption/decryption process. While the encryption task went smoothly using the encrypt function, I am encountering difficulties with decryption.

To troubleshoot, I attempted to decrypt the key from the backend service using online tools like this one, which successfully decrypted the hash message using the pre-stored public key.

Here's a glimpse of my current code:

decryptPayload(response: any) {
  const key = response.key;
  const payload = response.payload;

  const publicRsaKey = sessionStorage.getItem('rsa_public_key');

  const rsaDecrypt = new JSEncrypt();
  rsaDecrypt.setPublicKey(`-----BEGIN PUBLIC KEY-----
  ${publicRsaKey}
  -----END PUBLIC KEY-----`);
  const decryptAes = rsaDecrypt.decrypt(key);

  console.log('decrypted key: ', decryptAes);
}

Despite this implementation, the decrypted key always returns false, indicating decryption failure.

Has anyone encountered a similar issue while decrypting with the jsencrypt library using the public key? And is it indeed possible to decrypt a hash message using the RSA public key?

Answer №1

In my latest project, I implemented a method utilizing the JSEncrypt library that is capable of RSA public key decryption. However, it is important to note that this method only supports the PKCS1 padding scheme. I hope this code snippet proves helpful to individuals facing similar challenges in their own projects.

function convertBase64ToBigInt(value: Uint8Array) {
  let tmp = BigInteger.ZERO
  let multiplier = BigInteger.ONE
  for (let i = value.length - 1; i >= 0; i--) {
    tmp = tmp.add(multiplier.multiply(nbv(value[i])))
    multiplier = multiplier.multiply(nbv(256))
  }
  return tmp
}

function decryptWithPKCS1Padding(value: Uint8Array, pemPublicKey: string) {
  let decryptor = new JSEncrypt()
  decryptor.setPublicKey(pemPublicKey)
  let len = decryptor.getKey()['n'].bitLength() / 8
  let count = value.length / len
  let result = []
  for (let i = 0; i < count; i++) {
    let ret = decryptor.getKey().doPublic(convertBase64ToBigInt(value.slice(i * len, (i + 1) * len)))
    let tmp = ret.toByteArray()
    if (tmp[0] === 0) {
      throw new Error('Unsupported operation')
    } else {
      let index = tmp.findIndex((value, index) => {
        return value === 0 && index !== 0
      })
      result.push(...tmp.slice(index + 1))
    }
  }
  return Uint8Array.from(result)
}

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

Invoke a jQuery function once the ASP.NET grid has finished loading

I am struggling to trigger a jQuery function once the ASP.Net GridView is displayed. I have experimented with ready/load functions but none seem to work for me. The grid is contained within an Update Panel <asp:GridView ID="grdNumberPlan" runat="serve ...

Is there a way to select a checkbox in the main frame while in the $(document).ready of an embedded iframe?

I attempted this approach: $(document).ready(function(){ $(parent.top).find('.IAgreeCheckBox:first').prop("checked", true); }); but unfortunately, it did not work as expected. ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

What methods can I use to determine the height of an Angular directive?

For over an hour, I've been trying to accomplish a seemingly simple task: creating an Angular directive that can both retrieve and set the height of the current element. Additionally, this directive should be able to access the browser window in order ...

Tips for preventing tiny separation lines from appearing above and below unordered list elements

I am attempting to utilize twitter bootstrap to create a select-option style list. How can I eliminate the thin separation lines above and below the list of items? Refer to the screenshot: https://i.sstatic.net/1khEE.png Below is the visible code snippe ...

Is it possible for me to set a timer on the 'keyup' event in order to decrease the frequency of updates?

The code I currently have is functional: $wmdInput.on('keyup', function () { var rawContent = $wmdInput.val(); scope.$apply(function () { ngModel.$setViewValue(rawContent); }); }); Unfortunately, it appears to slow down my t ...

What is the process for showing and hiding text when a div is clicked?

Hey, I'm completely new to web development and decided to practice some of the concepts I've been learning about. I created a simple program that toggles between day and night. Clicking on the sun reveals the moon, and clicking on the moon revea ...

Can someone clarify if there is a distinction between using x.f.call(x, ...) and x.f(...) in JavaScript?

Reviewing some code reveals the following: this.f.call(this); Or in other scenarios: this.someObj.f.call(this.someObj); Is there a distinction between these and: this.f(); this.someObj.f(); Under what circumstances might the behavior differ? (e.g. if ...

Implementing Bootstrap JavaScript functionality within a Rails 7 application

My current Rails 7 application utilizes esbuild as the JS bundler and has bootstrap imported. I am facing an issue where I am unable to access any Bootstrap Javascript functionality outside of the main application.js file. For example, I am attempting to p ...

Guide on sharing Photo Blogs on Tumblr using the "tumblr.js" NodeJS module

I've been using the tumblr.js node module to interact with the Tumblr API, but I'm having trouble understanding what exactly should be included in the "options" when posting on my blog. So far, I've only used this module to retrieve my follo ...

The JSON property is not defined

After making an AJAX call to retrieve data, I receive a JSON Object instead of a string. When I log the object, all its properties appear correctly. However, when attempting to log one specific property, it shows up as undefined. Here is a snapshot of my ...

Is it possible to access the Windows certificate store using JavaScript?

Is there a way to access the Windows certificate store using JavaScript? I'm looking to create a web application that can validate user logins by reading their certificates. ...

Trouble with filtering in the Bootstrap table control feature

Incorporating the Filter Control extension with my bootstrap table is my goal. On the server side, I am utilizing django as the framework. The necessary CSS and JS files that I have included are: {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_jav ...

In JavaScript, a button is programmed with a rare 1.04% probability of directing to Page A and a much higher 98.96% likelihood of redirecting to Page

My goal is to create a button that, when clicked, will have a 1.04% probability of navigating to Page A and a 98.96% chance of going to Page B. The challenge I'm facing is in randomizing these results using JavaScript. I am fairly new to this language ...

Design personalized social media icons that allow users to easily share the link of the current page

Currently, I am working on creating a widget that includes social sharing buttons. The goal is for these buttons to share the URL of the current page when clicked on various social media platforms. For instance, I attempted to integrate a Twitter share but ...

Ways to adjust the focus on the ace editor

Currently, I am utilizing the ACE editor component from ajax.org within a jQuery tab interface. Within each tab will be a distinct ACE editor. The issue arises when switching to a new tab as the editor inside it fails to receive focus. I have managed to i ...

The deployment of the Fire-base Cloud Function was successful and error-free. However, the function does not appear to exist in the Firebase system

After deploying a JavaScript Cloud Function, it shows that the deployment is completed. However, when I check Firebase, the function is not there. Oddly, TypeScript Cloud Functions deploy successfully. I followed all the steps outlined in the original Fir ...

Fill in the text box based on the selected option from the dropdown menu

My HTML code snippet is as follows: <select name="plot_no" id="plot_no" class="dropdown validate_B"> <option value="">Select number of Plots to book</option> <option value="1">1</option> <opti ...

Unexpected identifier in the interface

Within my main.ts file, I've included the following code snippet : interface bodyInfos { height?: any; mass?: any; } const calculateBmi = (user: bodyInfos) => { return user.mass / ( user.height ** 2 ); }; let foo: bodyInfos; let bar: ...

Regular expression that allows alphanumeric characters and spaces, but does not permit spaces at the beginning or end of the

I need to create a regular expression that allows for a combination of letters, numbers, and spaces within a word, ranging in length from 3 to 50 characters, but without spaces at the beginning or end of the string. Here is the regex pattern I have come up ...