RSA Encryption for Text Exceeding Key Length

Hey Everyone,

I have been working on encrypting strings with JS and a public key. Utilizing the JSBN code has been helpful, but I am encountering an issue with creating a BigInt.

Here is what RSA.js does:

// Copyright (c) 2005 Tom Wu
var m = pkcs1pad2(text,(this.n.bitLength()+7)>>3); // obtaining the BigInt
if(m == null) return null; // checking for null
var c = this.doPublic(m); // encrypting the BigInt

The problem lies within the "pkcs1pad2" function. It includes a condition to verify if the length of the text exceeds the BitLength of the key. If it does, it returns; otherwise, it creates a BigInt.

// Copyright (c) 2005 Tom Wu
if(n < s.length + 11) { // TODO: fixing for utf-8
  alert("Message too long for RSA");
  return null;
}
var ba = new Array();
var i = s.length - 1;
while(i >= 0 && n > 0) {
  var c = s.charCodeAt(i--);
  if(c < 128) { // encoding using utf-8
    ba[--n] = c;
  } else if((c > 127) && (c < 2048)) {
    ba[--n] = (c & 63) | 128;
    ba[--n] = (c >> 6) | 192;
  } else {
    ba[--n] = (c & 63) | 128;
    ba[--n] = ((c >> 6) & 63) | 128;
    ba[--n] = (c >> 12) | 224;
  }
}
ba[--n] = 0;
var rng = new SecureRandom();
var x = new Array();
while(n > 2) { // random non-zero pad
  x[0] = 0;
  while(x[0] == 0) rng.nextBytes(x);
  ba[--n] = x[0];
}
ba[--n] = 2;
ba[--n] = 0;
return new BigInteger(ba);

I am unsure about the author's note "//TODO: fix for utf-8". Can someone provide an explanation and a solution?

Answer №1

Seeking to apply PKCS#1 v1.5 padding in accordance with the specifications outlined in PKCS#1. In order for encryption, the input of PKCS#1 v1.5 padding must be 11 bytes smaller than the modulus size:

M : message intended for encryption, an octet string of length mLen, where mLen <= k - 11

If the message surpasses this limit, RSA encryption cannot proceed. Typically, a solution is to encrypt using a symmetric cipher with a random key and then encrypting that key with RSA. This strategy is known as a hybrid cryptosystem.

The rationale behind this note is that JavaScript, akin to many scripting languages, faces challenges discerning between bytes and text. If s represents text, s.length is likely to return the number of characters rather than bytes. While intentional for weakly typed languages, it complicates cryptographic implementations in JavaScript.

In instances where a multi-byte encoding like UTF-8 is used, characters encoding to 2 bytes will expand the overall plaintext size in bytes, potentially causing calculation failures. Alternatively, characters beyond the ASCII range may be lost if they cannot be encoded into single bytes - a scenario likely when exceeding the ASCII (7 bit, values 0..127) character set boundaries glance at the code.

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

Implementing click functionality in React.js

Currently, I am in the process of learning React.Js and facing an issue with attaching an event to output something in the console. Despite my efforts, I am unable to get my function to trigger. Is there a method to attach an onClick event to a react div? ...

A guide to mocking the require function in electronJS

I'm facing a challenge while writing unit tests for my electron js application. For instance Let's say the code of my app looks like this: var app= (function () { function app() { var _this = this; this.open = function (dat ...

Identifying the various types in Typescript

In the process of developing a solution for Excel involving data from an Office API, I encountered the challenge of distinguishing between different types that a function can return. Specifically, the data retrieved as a string may belong to either a "Cell ...

What solutions are there for resolving the error "Cannot read property 'style' of null" in JavaScript?

My function is designed to update the progress bar based on the document's loaded value. However, for some reason, it seems that this specific element is unable to render. Despite my efforts, I cannot figure out why other div elements can be identifie ...

What is the best way to retrieve the fields from the JSON object generated by the API?

I'm having trouble displaying a specific field from the API response. While I can display the entire API response, I am struggling to show just one particular field of the object. Here is the API being used: The response received is as follows: { ...

Utilizing HTML5/JavaScript to send a text message from a mobile device

I am developing a mobile web application to be downloaded from various markets with a mini web server, capable of running on any operating system such as iOS, Android, Windows8, and more. My goal is to make the application as OS-independent as possible by ...

Ways to retrieve base64 encoded information from an image within an HTML document

On my registration form, users have the option to select an avatar from 2 choices: Select a default avatar Upload their own custom avatar This is how I have implemented it in my HTML page. <img id="preview" src="img/default_1.png"> The chosen av ...

Synchronization Problem with Jquery

Currently, I am adding a handlebars template to a div. In my code, I am using this line - test = $(".someClass:onScreen") I have verified that onScreen is working because when I mouse over the class it displays the content on screen. The reason for this ...

Sort an array of arrays based on the value of the second element in every inner array using JavaScript

Here is an array configuration I am working with: const arr = [ [500, 'Foo'], [600, 'bar'], [700, 'Baz'], ]; I am looking to reorganize this arr in alphabetical order based on the second element within each nested arra ...

Using React to set a background image that spans the entire height of the page

I'm trying to display a static image that spans the full height and width of my page, but it's not working as expected. Any ideas on how to fix this issue? You can find the image and code below. import Image from './image.jpg' var con ...

Redirecting visitors based on window size

I have created three individual pages for screen resolutions of 1024, 768, and 320 width. Is there a method to automatically direct the visitor to the appropriate page based on their screen resolution? The main reason I am not developing a responsive webs ...

Encountered an error while handling a promise: Unable to access null properties (specifically, 'useState')

I'm having trouble understanding why I keep encountering this error with the line const [isLoading, setLoading] = useState(true);. It's initially set to true so it shouldn't be undefined. export default async function GetProducts() { c ...

Using AJAX in Internet Explorer can be a bit tricky, but with

When using IE, I am attempting to implement a simple AJAX function that will update a table with values from the database whenever a dropdown selection is changed. Here is the script I am using: <script type="text/javascript"> function getXML() { v ...

Issue with Vue Socket.io: Client not able to receive messages sent from server

Currently, I am working on a multiplayer game project using Vue and Socket.io. The issue I am facing is that I can successfully send data from the client to the server, but for some reason, it's not working the other way around, and I'm strugglin ...

Troubleshooting Scroll Problems with Angular 5 and PDF.JS

I am working with Angular 5 and PDF.JS. Successfully downloaded a PDF and rendered it. Now, I need to display the PDF in a window by placing it inside a div. <div class="container border"> <div id="OptionsPanel" class="row lighten-1" *ngIf="isLoa ...

Tips for increasing the size of a textarea

I'm attempting to extend a textarea by adjusting the margin-top property, but it doesn't seem to be working as intended. Here is the code snippet in question: #sqlcontainerLoggedInPage2 { margin-top: 60px; } <div class="container-fluid" i ...

Focusing on a particular iframe

I am currently using the "Music" theme from Organic Theme on my WordPress site and have inserted this code to prevent SoundCloud and MixCloud oEmbeds from stretching the page width: iframe, embed { height: 100%; width: 100%; } Although the fitvid ...

What is the best method for transferring an audio file from an Express (Node.js) server to a Flask server

Successfully uploaded an audio file (e.g., WAV) at the frontend (React) and sent it to the backend (Express/Node.js). Here is my frontend code (App.js) import React, { useRef, useEffect , useState } from 'react' import VexFlow from 'vexflow ...

Display a list exclusively with radio button options

Currently, I am developing a module that allows the admin to view a list of candidates who have requested approval. The interface includes radio buttons for three different selections and a submit button. However, I would like to update this functionality ...

Implementing a 2D boolean array as a member variable in P5JS

While working in p5js, I am trying to create a 2-dimensional boolean array in JavaScript. The following code snippet successfully creates a 3x3 array of booleans set to false: var cells = Array.from({ length: 3 }, () => Array.from({ length: 3 }, () ...