PHP (specifically openssl) is effective for decrypting data, whereas javascript (cryptojs) has proven to be ineffective

Decryption is functioning using php/openssl, and I can successfully retrieve my plain data. Here is the specific call that is defined:

<?php

function decryptString($data, $key)
{
    return base64_decode(openssl_decrypt(base64_decode($data), "AES-256-CBC", $key, true, "h7oehNIHWGNIHxyN"));
}

function encryptString($data, $key)
{
    return base64_encode(openssl_encrypt(base64_encode($data), "AES-256-CBC", $key, true, "h7oehNIHWGNIHxyN"));
}

echo 'encrypted: ' . encryptString('my sample text', '7f7720b911c2ecbb22637ed7adef41e82d44b6a0') . "\n";

echo 'decrypted: ' . decryptString('rFWejB1Pj6W3Gh1bheFqDZPMO9POKbhGPOP6eAH9BSk=',        '7f7720b911c2ecbb22637ed7adef41e82d44b6a0') . "\n";

The output obtained from this code snippet is as follows:

encrypted: rFWejB1Pj6W3Gh1bheFqDZPMO9POKbhGPOP6eAH9BSk=
decrypted: my sample text

I attempted to replicate this function using cryptojs, but encountered errors such as "Malformed UTF-8 data" and other ambiguous issues. Here is the closest implementation I have achieved so far (currently facing a "Malformed UTF-8 data" error):

function decryptData(encrypted, pass) {
    // encrypted is a base64 encoded string
    let data = Buffer.from(encrypted, "base64").toString();  // Attempted this approach [ let data = crypto.enc.Base64.parse(encrypted); ]

    let key = crypto.enc.Utf8.parse(pass);
    let decrypted = crypto.AES.decrypt(data, key,
        {
            iv: crypto.enc.Hex.parse('h7oehNIHWGNIHxyN'), // Tried passing it as a simple string like this [ iv: 'h7oehNIHWGNIHxyN', ]
            mode: crypto.mode.CBC,
            padding: crypto.pad.NoPadding // Also tried with [ crypto.pad.Pkcs7 ]
        }
    );
let result =  decrypted.toString(crypto.enc.Utf8); //  Attempted this as well [ let result = decrypted.toString(crypto.enc.Base64) ]
}

Here is the error message that I am encountering:

/home/vagrant/PhpstormProjects/untitled3/node_modules/crypto-js/core.js:513
                    throw new Error('Malformed UTF-8 data');
                    ^

Error: Malformed UTF-8 data
    at Object.stringify (/home/vagrant/PhpstormProjects/untitled3/node_modules/crypto-js/core.js:513:24)
    at WordArray.init.toString (/home/vagrant/PhpstormProjects/untitled3/node_modules/crypto-js/core.js:268:38)
    at decodeBase64String (/home/vagrant/PhpstormProjects/untitled3/decryptor.js:13:25)
    at Object.<anonymous> (/home/vagrant/PhpstormProjects/untitled3/decryptor.js:19:1)

Despite trying various suggestions, I remain perplexed and unable to resolve the issue. Any assistance or guidance would be greatly appreciated.

Relevant questions that I have explored without success:

  • CryptoJS AES Unable to decrypt
  • Encrypt with PHP, Decrypt with Javascript (cryptojs)
  • AES decryption in crypto-js returns empty string

Update 1: I have provided a sample plaintext message, a complete php encryption/decription example, and the latest version of my code for reference.

Answer №1

When working with AES encryption, it is important to note that it is defined for 16/24/32 byte keys. If you are using a key that is 40 bytes long, PHP will automatically cut it to 32 bytes while CryptoJS does not, leading to a bug (#293) where the key is processed incorrectly without generating an error message but producing an inaccurate result.
Additionally, when passing the ciphertext, make sure it is in the form of a CipherParams object or Base64 encoded. The IV should be Utf8 encoded, PKCS7 padding must be applied, and the decrypted data will be in base64 string format (which will require further decoding).

Below is some CryptoJS code that can be used to decrypt the sample ciphertext:

function decryptData(encrypted, pass) {

    let decryptedWA = CryptoJS.AES.decrypt(
        encrypted,                                              // Pass ciphertext Base64 encoded (or as CipherParams object)
        CryptoJS.enc.Utf8.parse(pass.substring(0, 32)),         // Ensure key is truncated to 32 bytes
        {
            iv: CryptoJS.enc.Utf8.parse('h7oehNIHWGNIHxyN'),    // Encoding IV in UTF8
            mode: CryptoJS.mode.CBC,                              // default
            padding: CryptoJS.pad.Pkcs7                           // Apply PKCS7 padding
        }
    );

    let decryptedB64 =  decryptedWA.toString(CryptoJS.enc.Utf8); 
    let decrypted = CryptoJS.enc.Base64.parse(decryptedB64).toString(CryptoJS.enc.Utf8); // Decode the decrypted data from Base64

    return decrypted;
}

var ciphertext = "rFWejB1Pj6W3Gh1bheFqDZPMO9POKbhGPOP6eAH9BSk=";
var key = "7f7720b911c2ecbb22637ed7adef41e82d44b6a0";
console.log(decryptData(ciphertext, key));
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>

Note: It is crucial to understand that using a static IV is insecure, unless being used solely for testing purposes.

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

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

Looking for a method to transfer response.body information from an express server (server.js) to a React client (client.js)?

I'm currently working on a project that involves setting up a REST endpoint (POST) for the backend to send response data back to my React app. The goal is to construct an HTML page and then send that HTML back to the backend team. However, the challen ...

Encountering problems during the build process in Centos7 on a Vagrant machine after creating a symlink using npm install

While attempting to set up and compile a project from the package.json file using npm on a CentOS7 Vagrant machine, I encountered issues with symlinks. To resolve this problem, I utilized npm install --no-bin-links which successfully installed the packages ...

Is it possible to extract all parameters, including nested or within arrays, from a Swagger File using Node.js?

Looking for a method to extract and interpret data such as parameters from a Swagger file. Specifically, I am working with the Petstore Swagger API ( ). The definitions within the file contain references to other components, like parameters. One example ...

An error occurred while trying to read properties of undefined (specifically 'getStackAddendum') after upgrading the react-scripts version from 3.4.0 to 5.0.0

Currently in the process of upgrading react-scripts from version 3.4.0 to version 5.0.0, I encountered an issue when running 'npm run start' which resulted in a Type Error: Cannot read properties of undefined (reading 'getStackAddendum' ...

Issue arises when attempting to run npm start on Windows 10 due to node-gyp failing

After setting up Node.js version 12.18.1 and Python v3.8.1 on my Windows 10 system, I encountered an issue when trying to run npm install in a project: gyp ERR! configure error gyp ERR! stack Error: Command failed: C:\Program Files (x86)\Python&b ...

Options or menu in Whatsapp-Web.js

I am currently working on creating an app using node.js with the goal of sending WhatsApp messages to my client list. To achieve this, I am utilizing WhatsApp-Web.js. While I have successfully included media messages and text captions, I am encountering d ...

"Use npm to install a package from a tarball file that was generated using

After creating a compressed file with npm pack, I attempted to install it but encountered an error message from npm: D:\tmp>npm install package-0.0.1.tgz npm WARN saveError ENOENT: no such file or directory, open 'D:\tmp\package.jso ...

Utilizing Javascript Regular Expressions to extract specified parameters from URLs with specific patterns

I am facing a specific issue with pure vanilla javascript. My task is to extract the values of A, B & C from various URL patterns, excluding any instances where the value is "XX". A, B, and C are static words that can appear in different positions wit ...

Warning - A memory leak in the EventEmitter has been detected, with 11 wakeups

Issue: (node) warning: possible EventEmitter memory leak detected. 11 wakeup listeners added. Use emitter.setMaxListeners() to increase limit. The dilemma arises on whether to address this error and adjust the limits or if it can be disregarded. Ultimate ...

What steps can be taken to eliminate a npm install error?

I have been attempting to execute the following project: https://github.com/kentcdodds/react-in-angular This repository serves as an illustration of incorporating React into AngularJS. It consists of three tags that demonstrate the process of transitio ...

What steps are necessary to create an npm package utilizing three.js without any dependencies?

I have a challenge - I am trying to create an npm package that generates procedural objects for three.js. The issue I'm facing is how to properly include three.js in my code. I attempted to establish a dependency and use something like const THREE = r ...

`Express.js Controllers: The Key to Context Binding`

I'm currently working on a project in Express.js that involves a UserController class with methods like getAllUsers and findUserById. When using these methods in my User router, I have to bind each method when creating an instance of the UserControlle ...

Having trouble getting the ValidatorPipe to function properly in my nest.js application

Issue Description There is an issue with the current behavior where initializing a validation pipe for a request body does not reject invalid types as expected. Desired Outcome The expected behavior should be that when a user provides a value that does n ...

Testing node.js express route/controller with promises for unit testing

After transitioning from using callbacks to promises in my express app's REST API, I've encountered difficulties testing routes/controllers with asynchronous promise behavior. Below is a snippet of the code that requires unit testing: var handle ...

What is the process of transferring user product information from a node.js application to Paypal?

In my node.js application, I have implemented a button for users to purchase products. I'm exploring ways to pass the product details, such as amount, to PayPal for payment processing. Are there any existing libraries or methods that can assist with t ...

Using TypeScript with Node.js and Sequelize - the process of converting a value to a number and then back to a string within a map function using the OR

Currently, I am facing a challenge in performing addition on currency prices stored as an array of objects. The issue arises from the fact that the currency type can vary among 3 different types within the array of objects. The main hurdle I encounter is ...

Exploring the intricacies of making HTTP GET requests in Node.js

Seeking to grasp the inner workings of the http.get function call in this scenario, here is a code snippet I am currently experimenting with: var http = require('http'); var urls = ['http://www.google.com', 'http://w ...

Ensuring Code Execution Order in NODE.JS

I've encountered an issue with my code that involves parsing a pcap file, storing the data in an array data = [], and then writing it to a JSON file: var fs = require("fs"); var pcapp = require('pcap-parser'); var hex = ""; var data = []; v ...

Issue with Axios in Vue app: Only receiving network errors for Post requests

Using the Following Stack Express,Vue,SQL,Axios Successful GET request in postman and Axios Error encountered with POST request, see attached screenshots To test backend functionality, data was sent directly from a form <form action="url" me ...