Encrypting and decrypting data using RSA in TypeScript

Currently, I am utilizing Angular 4 to develop the front end of my application. For authentication, I have integrated OAuth2 on the backend (which is created using Spring in Java), ensuring that only authorized individuals can access my app.

However, there is a major concern as passwords are stored in plain text format in the backend server logs, making them vulnerable to interception by a Man-in-the-Middle (MITM) attack until SSL is implemented.

To address this issue, I have made the decision to encrypt the transmitted passwords using RSA. While my backend implementation is complete, I am facing difficulties finding modern libraries that offer a reliable API for encryption/decryption with RSA key-pairs.

I have explored options like the 'crypto' module, but it is no longer supported in ECMAScript 6. The 'crypto-js' library only supports AES and certain hash functions like MD5/SHA.

Answer №1

At last, I have discovered a solution after installing a few things.

npm install buffer
npm install crypto-browserify

Now to put it into action:

import {config} from "../app.config";
import {Buffer} from 'buffer/';
import * as crypto from "crypto-browserify";

export class RsaService {
  private privateKey: string;
  private publicKey: string;
  private enabled: boolean;

  constructor() {
    this.privateKey = config.authentication.rsa.privateKey;
    this.publicKey = config.authentication.rsa.publicKey;
    this.enabled = config.authentication.rsa.enabled;
  }

  isEnabled(): boolean {
    return this.enabled;
  }

  encrypt(plaintext: string): string {
    if (!this.enabled)
      return plaintext;

    let buffer = new Buffer(plaintext);
    let encrypted = crypto.privateEncrypt(this.privateKey, buffer);

    return encrypted.toString('base64');
  }

  decrypt(cypher: string): string {
    if (!this.enabled)
      return cypher;

    let buffer = Buffer.from(cypher, 'base64');
    let plaintext = crypto.publicDecrypt(this.publicKey, buffer);

    return plaintext.toString('utf8')
  }
}

Answer №2

When network logs are captured in specific locations, it becomes possible to retrieve the entire http pipeline as pure text. Once SSL is functioning on a particular layer of communication, stream can be monitored at a higher layer to access this information. This addresses some previous comments.

In terms of architecture, it makes total sense to prioritize data security from unauthorized access. In theory, I recommend the following approaches:

1) Develop your own encryption method and implement it on both ends. Even something as simple as matrix multiplication could suffice for non-critical transmissions.

2) Utilize cryto-js on both sides by incorporating a segment of JavaScript code within your Java code for password (de)encryption purposes.

3) Integrate an external authentication/authorization system such as Google, Twitter, Facebook, IBM BlueID, Azure, AWS, or even your own domain controller. Alternatively, consider combining an external entity with your domain controller through Federation.

In conclusion, there are numerous solutions available - ranging from creating custom applications to implementing complex structures. It's important to take precautions when handling sensitive data.

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

"Element of design focused on style and arrangement

After reviewing the material ui documentation located at https://material-ui.com/components/typography/ I attempted to utilize the Typography component in the following manner: <Typography variant="h1" component="h1"> Hello World </Typography& ...

Is it possible to authenticate a user in Firebase using Node.js without utilizing the client side?

Can I access Firebase client functions like signInWithEmailAndPassword in the Firebase SDK on the server side? Although SDKs are typically used for servers and clients use JavaScript, I need a non-JavaScript solution on the client side. I have set up the ...

What is the best way to utilize @Input in components that have been generated using ComponentFactoryResolver?

Is there a way to specify an @Input property for an Angular 2 component that is created dynamically? I am utilizing the ComponentFactoryResolver to generate components within a container component. For instance: let componentFactory = this.componentFacto ...

Encountering a 404 Error When Making an Ajax Request in Spring MVC

Looking to implement a basic login form using Spring MVC and an APIResponseModel class with Status, Message, HTTPStatus variables. After submitting the credentials, receiving a 404 ajax response, although the Controller returns {"status":"20 ...

Utilizing Inquiries within Arrays

I've been working on a quiz application and I have successfully built the array with questions and answers. However, I'm facing some challenges in getting the next question to display after clicking the submit button. Here is a snippet of the cod ...

Utilizing NodeJS and Express to efficiently share sessions across various routes

I have a Node.js web application built with Express that has multiple routes. These routes need to be able to access and share the session data when interacting with users. The routes are separated into different js files from the main app file, app.js. I ...

What is the best way to incorporate this HTML and script into a React component?

After receiving the embedded HTML and script from a platform, I discovered that a button triggers the script. It was originally designed to be embedded on a website, but I am attempting to integrate it into a React application. Here is the code provided fo ...

The Ink CLI is anticipating the component to be a function

Currently delving into the world of the Ink library for constructing a console application in Javascript. Despite having experience with React, this is a different ball game. Some of the nuances are proving to be quite perplexing. I've managed to get ...

The issue of slides overlapping in a Javascript slideshow during auto play mode

I encountered an issue while creating an automatic slideshow with 4 slides. Upon autoplay for the first time, slide 1 overlaps slide 4, as well as slide 2 and 3. This only happens once after the site loads. However, on subsequent playthroughs or when using ...

Creating a personalized confirmation function using JavaScript

Here is a function I've created to generate a confirmation box. The issue I'm facing is that the function doesn't wait for the user to click before returning true/false based on the onclick events. So, how can I solve this? function Confi ...

What is the process to access array elements in AngularJS?

When coding in HTML, <select class="element-margin-top" ng-model="vm.selectedRole" ng-options="(roleName,enabled) in vm.roleNames"> <option value="">All Roles</option>{{vm.roles[0]}} </select> I am tryin ...

Lazy loading a React grid gallery as you scroll

Currently, I am utilizing React grid gallery to showcase images from this repository: https://github.com/benhowell/react-grid-gallery. However, I am encountering an issue with lazy loading when the user scrolls on the page. <Gallery images={this ...

How to modify the background color within the mat-menu-panel

Incorporating angular 9 and less into my current project, I have encountered an issue with a mat-menu-panel where my mat-menu-item is located. While I have successfully changed the color of my mat-menu-item, I am now faced with the challenge of changing th ...

Disabling a chosen option within a dropdown menu

`Hello there, I am just starting out with JavaScript and jQuery. Currently, I am developing a web application for ordering food and drinks. I have a dropdown menu for selecting breakfast items and the quantity. When the "add" button is clicked, a dynamic ...

Modifying the color of drawings on a Javascript canvas

I am currently working on developing a drawing board using HTML and JavaScript (Node.js on the server side). One challenge I'm facing is implementing a color picker that allows users to change the paint color dynamically. While I could hard code the c ...

Add an input element to a form fieldset by employing vue

In my form, I have a staged approach with 3 fieldsets that only appear when the "Next" button is clicked. Now, in the third fieldset, I need to add input elements based on keys extracted from an external json object. Data: data: () => ({ c ...

Difficulty establishing audio calls with Internet Explorer using PeerJS

I successfully implemented a user-to-user audio call system by following the steps outlined in this guide: The system is up and running flawlessly on my website while using Google Chrome. However, I encountered an issue when trying to connect to a user o ...

The POST request is not functioning. An error has occurred: Unable to retrieve response data - no content is available for the preflight request

Having trouble making a post request from my client side to the back-end. Even with the new movie hardcoded, it keeps returning an error stating that there was a failure in loading the response data. Below is the code for the front-end: //Fetch request t ...

Can we include an option to display all pages in one row on a single page?

Is it possible to include an option to display all rows alongside the current options of 10, 15, and 100? I've been unable to locate this feature in the documentation: Check out the Codesandbox example: https://codesandbox.io/s/muidatatables-custom-t ...

The functionality of the anchor tag is restricted in both Chrome and Safari browsers

I'm having an issue with HTML anchor tags not working properly in Chrome and Safari. Instead of scrolling up, the page scrolls down when clicked. Here is the HTML code I'm using: <a id="to-top"></a> <a class="button toTop" href="# ...