Exploring the power of Blowfish encryption with Java and JavaScript

I am facing an issue where I need to encrypt data using Blowfish on a java-based server and send it to a client. Despite successfully encrypting the data, I am unable to decrypt it on the client side.

Below is my Java code snippet:

byte[] kd = key.getBytes("UTF-8");

SecretKeySpec ks = new SecretKeySpec(kd, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, ks);

byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));

String str = new String(encrypted, "UTF-8");

For the JavaScript library, I opted for this one.

out = blowfish.decrypt(code, skey, {cipherMode: 1, outputType: 0})

However, I am getting strange characters as output. What could be wrong with my implementation?

UPDATE: The following revised code works flawlessly:

byte[] kd = key.getBytes("UTF-8");

SecretKeySpec ks = new SecretKeySpec(kd, "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, ks);

byte[] encrypted = cipher.doFinal(text.getBytes("UTF-8"));

String str = new String(Base64.encodeBase64(encrypted), "UTF-8");

JS counterpart:

out = blowfish.decrypt(code, skey, {cipherMode: 0, outputType: 0})

Answer №1

When transmitting text containing null bytes to a browser, it can result in various unexpected issues. To avoid this, it is recommended to encode the data using BASE64 before sending it to the client and then decoding it on the client side.

Another consideration is when using new String(encrypted, "UTF-8");, as the encoded byte array may contain invalid UTF-8 sequences. In such cases, using

new String(encrypted, "iso-8859-1");
is a better option as it provides a direct mapping for arbitrary bytes. However, keep in mind that the presence of null bytes could potentially cause confusion in certain components along the way.

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

Ways of extracting specific information from a JSON file with the help of jQuery

I am currently attempting to parse a JSON file that is stored locally on my system using jQuery. I am specifically interested in retrieving certain data from the file, which is structured like this: {"statements":[{"subject":{"uriString":"A","localNameIdx ...

Transferring data from an Angular 2 component to a service

I am trying to pass data from an Angular component to a service and utilize the service's methods to manipulate it. Here is an example: class SomeComponent { public info: Array<any> = MyData; constructor(private myService: TablePag ...

Issue with Angular binding not updating after being assigned in promise.then() function

Within my angular application, I have a $scope variable labeled as user which contains a name property. Whenever I click on a link to set this user variable to "test": <a href="#" ng-click="setUser()">Set User</a> Using the following functio ...

In my Node.js/Express.js application, I have a directory that holds various images. Whenever I attempt to view these images via their URL, I encounter a 404 error message

In my Node.js/Express js project, I have the following folder structure: root ----bin ----controllers ----middleware ----models ----node_modules ----public --------images ------------test.png ----routes ----views I am currently trying to determine the cor ...

AngularJS making a HttpPost request resulting in a 500-Internal Server Error

I'm currently working on an application where I need to include a user in the database which requires a POST operation. However, every time I try to run the application, I encounter a 500-Internal Server Error for the POST API call. Here is a snippe ...

Ensure to wait for the user ID before accessing Firestore collections

Trying to wrap my head around rxJs and experimenting with using the where query in Firestore collection. However, I've run into an issue where the output of this collection is dependent on retrieving the user ID from Firebase Auth. Here's what I ...

Leveraging the Wikia API

I've been attempting to utilize the X-men API on Wikia in order to gather the name and image of each character for use in a single page application using JavaScript. You can find the link to the wiki page here: Despite my efforts, I am struggling to ...

What could be causing a momentary 404 error when I click on a next.js `Link` that connects to an API endpoint before redirecting to the intended page?

Hello there, I recently followed a tutorial on adding authentication with Passport to Next.js from this resource: https://auth0.com/blog/next-js-authentication-tutorial/ However, I encountered a minor issue. When I click the "/login" Link in my Next.js ...

Difficulty arising from the final column of average sums - Information extracted from JSON using Angular JS

I am facing a problem with calculating the average total. I need to determine the average sum using a specific formula, but the code provided does not calculate the last column of Average. I am looking for a desired result and would appreciate any assistan ...

New parents, same name D3.JS

Currently utilizing d3.js to visualize a tree structure. When parsing the JSON object containing nameOfNode and NameOfParent, encountering an issue when there are two nodes with the same name. Seeking recommendations on the most effective way to address ...

What is the best way to send an array of objects to a Jade template?

I'm looking to retrieve an array of objects from MongoDB and pass it to the client... Here is an example object: var objeto_img= { name:'name of the file', ...

"Hey, getting an error stating 'require is not defined' while attempting to configure the .env file. Need some help here

I am currently working on setting up a .env file to securely store the credentials for my Firebase database within a vanilla JavaScript project. Despite following various tutorials and referencing the documentation for dotenv, I continue to encounter an er ...

Using JQuery to loop through elements when clicked

I've been experimenting with different methods to iterate through a series of 4 li elements, each having a class of "item_n" where n is a number from 1 to 4. I want the iteration to increase by 1 with every click. Despite my efforts, my code isn' ...

What is the best way to troubleshoot a $http asynchronous request?

Is there a way to pause the program execution in AngularJS $http call after receiving a successful response? I've attempted to set a breakpoint at that point, but it does not halt the execution. I've also tried using the debugger directive, but ...

Looking to align the labels of material UI tabs to the left instead of their default center alignment? Here's how

Is there a way to align material ui tab labels to the left instead of center by default? View an image demonstrating center aligned tab labels here ...

Troubleshooting: Issue with v-link to classname in Vue.js

This is the code I am working with: <div v-link="'/work/' + {{data.useClass}}" class="itemImg {{data.useClass}}"> When rendered in the browser, it looks like this: <div class="itemImg x50"> The expectation is that class="itemImg { ...

Choosing a lone column in amcharts 4

Is there a way to highlight just one column and unhighlight any previously highlighted columns in an amCharts 4 Column chart? I've been attempting to adjust the colors of all the columns before highlighting the target column, but it doesn't seem ...

Using data across multiple instances in node.js EJS partials

I need some advice regarding my nodejs project. I have created a sidebar partial that requires user data to be displayed on it. This sidebar is utilized across multiple pages in the project. However, currently, I have to include the user data in every func ...

Display HTML content using JavaScript only when a checkbox is selected

Currently, I am updating an HTML form to show additional subsets of questions based on the selection of a "parent" checkbox. The current implementation works well, but I am wondering if there is a more efficient way to achieve this without having to rewrit ...

What is the most efficient method in React for displaying an array as a table and wrapping every set of five elements with a <tr> tag?

Currently, I am working on rendering a table in React from an array of objects. My approach involves mapping the array to create table elements as shown below: var objects = response.data; var arrayOfTableElements = [] ...