How to decipher strings encrypted using JS crypto in Java

How can I translate this JavaScript code into Java using javax.crypto.xxx?

    encryptString : function encryptString(str, password) {
        var cipher = crypto.createCipher("aes128", password);
        return cipher.update(str, "binary", "base64") +
            cipher.final("base64");
    },

    decryptString : function decryptString(str, password) {
        var desipher = crypto.createDecipher("aes128", password);
        return desipher.update(str, "base64", "binary") +
            desipher.final("binary");
    }

I plan to encode in JS and decode in Java, as well as vice versa. Both 'str' and 'password' variables are strings, with the 'password' being 16 characters long.

It seems that the createCipher(algorithm, password) method utilizes a unique approach to generate raw key and IV, which may not be standard across different platforms. Switching to createCipheriv(algorithm, key, iv) could provide a more versatile solution. For more information, check out: http://nodejs.org/api/crypto.html#crypto_crypto_createcipheriv_algorithm_key_iv I will make sure to update with the latest information soon.

Answer №1

Here are the steps to encrypt and decrypt data in JavaScript and Java using the Crypto library for JS and javax.crypto for Java.

If cross-environment compatibility is not a concern, you can start quickly by using the createCipher(algorithm, password) method in your JavaScript code. However, this approach lacks portability as it doesn't specify how the raw key and initialization vector are derived from the password.

To achieve portable encryption/decryption in JavaScript, switch to using the createCipheriv(algorithm, key, iv) method:

    encryptData : function encryptData(data, encryptionKey, iv) {
        var cipher = crypto.createCipheriv('aes-128-cbc', encryptionKey, iv);
        var encryptedData = cipher.update(data, 'binary', 'base64');
        var remainingEncryptedData = cipher.final('base64');
        return encryptedData + remainingEncryptedData;
    },

    decryptData : function decryptData(data, decryptionKey, iv) {
        var decipher = crypto.createDecipheriv('aes-128-cbc', decryptionKey, iv);
        var decryptedData = decipher.update(data, 'base64', 'binary');
        var remainingDecryptedData = decipher.final('binary');
        return decryptedData + remainingDecryptedData;
    },

For Java, here is the equivalent code snippet that performs the same operations:

public static String encryptData(String plainText, byte[] key, byte[] iv) throws Exception
{
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
    IvParameterSpec ivParams = new IvParameterSpec(iv);
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivParams);
    byte[] encryptedData = cipher.doFinal(plainText.getBytes());
    return new String(Base64.encodeBase64(encryptedData));
}

public static String decryptData(String encryptedText, byte[] key, byte[] iv) throws Exception
{
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
    IvParameterSpec ivParams = new IvParameterSpec(iv);
    cipher.init(Cipher.DECRYPT_MODE, secretKey, ivParams);
    return new String(cipher.doFinal(Base64.decodeBase64(encryptedText)));
}

Answer №2

We encountered a similar issue and decided to tackle it by encrypting the voucherCode on the Java side before sending it to the front end. It was crucial to ensure the security of the voucher code through encryption.

On the front end, a third-party JavaScript library required the voucherCode in a way that allowed for decryption to retrieve the original value.

This is how we approached the solution:

On the Java side

import javax.xml.bind.DatatypeConverter;

    public class Controller{

     @RequestMapping("voucherCode")
     public String getVoucherCode{
       String voucherCode = voucherService.getVoucherCode()
             return  DatatypeConverter.printBase64Binary(voucherCode.getBytes("UTF-8"))

}
    }

For example, if the voucher code is "50%OFF," the above code will encode it as NTAlT0ZG.

Once we have the encoded value on the front end, we can retrieve the original value using JavaScript:

window.atob("NTAlT0ZG") // this will return 50%OFF

This approach allows for seamless encryption/decryption between Java and JavaScript.

The window object provides two methods for encryption and decryption:

 window.btoa("50%OFF") // returns NTAlT0ZG
    window.atob("NTAlT0ZG") // return original value as "50%OFF"

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 process for retrieving data from a server and filling an SQL database on an Android device?

My goal is to retrieve data from Firebase Firestore (an array of names), create an SQL table, and populate the table with data from the server. Every time the app is launched, I need to compare the version number from Firebase with the SQL database version ...

Filtering the values of an array nested within objects

Imagine having a vast database of 10,000 cards and attempting to filter them based on the banlist_info.ban_ocg === "Forbidden" { id: 15341821, name: 'Dandylion', type: 'Effect Monster', desc: 'If this card is sen ...

"I am having trouble with req.body in my Express JavaScript application as it is not returning the data from POST requests. Can

Being new to building an express server in NodeJS, I've been able to work on POSTs and GETs using routes and controllers. However, I'm puzzled as to why req.body is showing {} in the terminal. It seems like no data is being received from AJAX. Ca ...

Displaying Google Picker results in an error due to an invalid origin value

After utilizing the same code for a period of 2 years, we are encountering an issue where the picker no longer displays. I have consulted resources on Google Picker API Invalid origin but haven't been able to successfully set the origin value. The cod ...

The 'checked' property cannot be bound to 'mat-button-toggle' as it is not recognized as a valid property in Angular 9

I am encountering an issue with my Angular 9 application. I have integrated angular-material and imported the MatCheckboxModule correctly in the module. Here is the version of the material package I am using: "@angular/material": "^10.2.0&q ...

I am looking for a way to automatically close an existing window and open a new window whenever a button is clicked in Angular. How can I achieve this

Looking to use window.open() to open a new window, but need to ensure that if the same window is already open from before, it must be closed before opening a new one. ...

Adding several entries into mysql with the assistance of php

I've been attempting to input multiple records into my database table, but every time I try, all I see are zeros(0) inserted into the fields. Here's what I attempted: I used a foreach loop for insertion, but unfortunately it doesn't seem to ...

Dealing with Wrapped Exceptions and Utilizing the getCause() Method in Spring Framework's @

Looking for a simple solution to handle wrapped Exceptions using @ExceptionHandler. I have a custom org.springframework.core.convert.converter.Converter that I use to convert a @PathVariable. If the input is outside the standard range, it throws a custom ...

Is the order of items guaranteed when reading a file in node.js?

Within my node.js application, I have a test data file which I utilize to populate certain inputs. This file is structured as an array of objects. To read the data, I implement the following: data = fs.readFileSync(fileName, "utf8"); An excerpt from my ...

Java Game Lag becomes a major hurdle to smooth gameplay

Currently working on a Java game and facing performance issues. After benchmarking the paint cycles and game logic, everything seems to be on track. However, there is still an annoying lag present when scrolling, zooming, and clicking, especially when mo ...

Is it possible to utilize a global constant in Angular without the need for injection into the controller?

I have defined a constant object in coffeescript: angular .module 'main', [] .constant 'CONFIG', IMAGEROOT: 'http://some-img.s3-website-ap-southeast-1.amazonaws.com/' When using the constant in html, I write it like ...

Issues encountered when utilizing a provider alongside a controller for implementing Highcharts visualizations in angularjs

I've been working on an Angular web application that incorporates highcharts (highcharts-ng) integration. My approach was to set up a factory provider where I defined my chart configuration options object: angular.module('socialDashboard') ...

Encountered an unexpected element during JSON unmarshalling that caused a javax.xml.bind.UnmarshalException with the URI "" and a local context

When attempting to Unmarshall a JSON to Java Object, I have come across several posts discussing parsing XML. Therefore, I believe my question is unique. My Java class includes the following annotations: @XmlRootElement(name = "cpResponse") public class ...

Interactive Map Markers on JMapViewer with OpenStreetMaps

I'm currently working on creating a map using JMapViewer within the Swing framework. The map contains various MapMarkerDots that represent cars. My goal is to update the positions of these markers so they appear to be moving around the map. However, I ...

Incorporating CSS classes conditionally in an Angular child component using input values

I am currently using a list component: <section class="p-10 flex flex-col gap-10"> <p class="text-xl font-black text-blue-700">Transfer history</p> <div class="flex flex-col gap-10"> @for(item o ...

Issue encountered when trying to access WCF Service on Android Device

Having trouble POSTing data to my database using a WCF service. No matter what I try, nothing seems to work. As a beginner in Android development, I'm struggling to debug the issue. Any help would be greatly appreciated. Here is the code snippet: W ...

After being redrawn, the line on the canvas vanishes

After updating the angle value, the line is quickly redrawn correctly but then disappears. It seems like the input value may be getting refreshed and set to undefined again. How can I ensure that the line retains the correct angle? <script language=" ...

Guide on adjusting the darkness of a MaterialUI Avatar component image and adding text to it

I'm currently working with the Avatar component from Material UI along with Tailwind CSS. I found that by simply adding the image URL to the src, it displays the avatar successfully. <Avatar alt="Cindy Baker" src="https://mui.com/sta ...

What is the most efficient method for showcasing a downloaded image in a ListView?

I have implemented a custom adapter to show an ImageView and two TextViews in each row of a ListView. Inside the getView method of the adapter, I have included the following code for handling the ImageView: final ImageView img = (ImageView) view.findView ...

Errors and warnings caught off guard while running json-server with the --watch flag

I'm having some trouble using json-server in the following way: $ json-server --watch db.json Every time I try to run that command, I encounter errors or warnings depending on the version of json-server that is installed: 1.0.0-alpha.1-1.0.0-alpha.1 ...