Challenge with decrypting data using Mysql's AES_ENCRYPT and client-side Javascript Aes.Ctr.decrypt

The issue at hand

I have confidential data stored in a MySQL database, and I am looking to encrypt this data when performing a SELECT query. Subsequently, I aim to decrypt it on the client-side using JavaScript.

Here is an example:

MySQL SELECT query:

SELECT HEX( AES_ENCRYPT( 'text', 'secret' ) )

Result:

CAC9877FC9203920EC4C0E8F1CB5C49C

I have explored utilizing two libraries for implementing client-side AES decryption: Crypto-js and AES Advanced Encryption Standard.

While attempting to align the encryption parameters between MySQL and Crypto-js library as described in this link, I encountered issues with my solution not working as anticipated.

Even with the second library, I faced similar challenges.

Sample code using Crypto-js:

CryptoJS.AES.decrypt(
    'CAC9877FC9203920EC4C0E8F1CB5C49C',
    'secret',
    {
        mode: CryptoJS.mode.CTR,
        padding: CryptoJS.pad.ZeroPadding
    }
);

Result:

WordArray.t.extend.init 
{
    words: Array[8], 
    sigBytes: 24, 
    init: function, 
    toString:function, 
    concat: function…
}

    sigBytes: 24
    words: Array[8]
    0: -140444473
    1: 2005116093
    2: -506226828
    3: -210568886
    4: -277754559
    5: 880241217
    6: 598097705
    7: -2102072885
    length: 8
    __proto__: Array[0]
    __proto__: s

Client-side decryption implementation using Advanced Encryption Standard library:

Aes.Ctr.decrypt(window.atob('CAC9877FC9203920EC4C0E8F1CB5C49C'), 'secret', 128);

Result: "40^¡®bÞøgÈ"

Aes.Ctr.decrypt('CAC9877FC9203920EC4C0E8F1CB5C49C', 'secret', 128);

Result: "ӽ+) ¾ %[ø\3 "

What could be causing this discrepancy?

UPDATE

Following advice from Thomas, I have opted to implement PHP server-side encryption instead of relying solely on MySQL encryption.

After extensive trial and error, I successfully found a solution that enables me to encrypt data on the server-side using PHP and decrypt it client-side using the CryptoJS library.

See below for code examples:

PHP

<?php
class Encryption
{
     public function encrypt($text){
        $key = md5("secret");
        $iv = utf8_encode("1234567812345678");
        return mcrypt_encrypt(
            MCRYPT_RIJNDAEL_128, 
            $key, 
            $text, 
            MCRYPT_MODE_CBC, 
            $iv);
    }
}

JavaScript

function decryptData(text){
    var hash = CryptoJS.MD5('secret');
    var key = CryptoJS.enc.Utf8.parse(hash);
    var iv = CryptoJS.enc.Utf8.parse('1234567812345678');
    var dec = CryptoJS.AES.decrypt(
            text, 
            key, 
            {
                iv: iv, 
                mode: CryptoJS.mode.CBC, 
                padding: CryptoJS.pad.ZeroPadding 
            });
    return CryptoJS.enc.Utf8.stringify(dec);
}

How to use it

Server side(PHP):

$sensitiveText = "Some sensitive information";
$encString = Encryption::encrypt($sensitiveText);
echo $encString;

Client side(JavaScript):

var decrypted = decryptData('<?=$encString;?>');

Make sure to load the appropriate CryptoJS libraries: CBC && ZeroPadding. A helpful resource for me was: this post. It provides insights on cryptographic testing with PHP mcrypt and offers guidance for different scenarios as well.

Answer №1

While the MySQL documentation cites ECB as the encryption mode utilized in MySQL, your decryption code is actually using CTR.

It may be advisable to switch to ECB for consistency.

Important Note: Avoid Using ECB Encryption

ECB is considered an insecure encryption mode and should not be used for encrypting sensitive data.

For a more secure approach, consider performing encryption in your server-side code rather than in MySQL, and opt for a stronger encryption mode such as CBC or CTR for better security (I recommend CBC or CTR for simplicity).

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 best way to create a fixed sidebar or top bar that remains visible as I move to different pages?

Whenever I navigate to other pages, the sidebar mysteriously disappears. As I work on my project about an admin page, I'm wondering if it's necessary to include every single page? ...

Get Onsen UI 2 up and running without the need for Angular

Is it possible to install Onsen UI 2 without Angular? I have tried following various guides from , but when attempting the JavaScript method (> npm install onsenui) I consistently encounter a ReferenceError: angular is not defined. How can I properly in ...

Tips for extracting information from a JSON file using $routeParams in AngularJS

https://i.stack.imgur.com/NQCpy.png I am currently encountering an issue with retrieving data using $routeparams. Here is a description of my problem: Retrieving the URL to redirect console.log($routeParams); console.log($routeParams.json_url); $.getJS ...

Using Angular to Dynamically Change Webview URLs

I've been attempting to update the URL of my webview by invoking a function with AngularJs, but unfortunately, I haven't been successful. Below is my Angular class: app.controller("speechController", function($scope){ $scope.page = 'in ...

The challenge with using Telerik Rad Textboxes in conjunction with JavaScript

I am facing an issue where the server data is not displayed in a Rad Textbox until I click on it using JavaScript. The data is being populated correctly inside the textbox, but it remains invisible until clicked. function fillTextBox(name, sku, plu, nam ...

Recursive functions that request input from the user

Currently in the process of developing a fun little script to help me organize and rate the movies in my personal collection. Among my list are a number of different movie titles that desperately need to be organized. The plan is to implement a merge-sort- ...

In Node.js and JavaScript, attempt to access a variable within the catch block in order to remove a Cloudinary image in the event

I've encountered a situation where I successfully upload an image to cloudinary, but run into a MongoDB error afterwards. In this case, I need to delete the image from cloudinary. However, I'm unsure of how to access the value of "cloudinary_id" ...

What is the reason for encountering a division by zero exception when opting for REPLACE instead of SELECT?

For years, I've been using this rather complex SQL statement that has always worked perfectly: INSERT INTO aggregate ( channel_id, type, timestamp, value, count ) SELECT channel_id, 1 AS type, MAX(agg.timestamp) AS timestamp, COALESCE( ...

Updating the options list of an Autocomplete component post-render: A step-by-step guide

I've encountered an issue with a function that retrieves a JSON array from a URL containing a list of options to be displayed in my Autocomplete component. function DisplayOptions() { async function GetOptions() { options_list = await fetc ...

Validating groups of fields using Angular fieldsets

AngularJS validation is working well with ng-required. However, I am interested in checking if all the form elements within my fieldset are valid. <form> <fieldset> <legend> Part one <img src="/co ...

"Troubleshooting: Difficulty with hover function in jqgrid not functioning on colored rows

My JQGrid setup includes the following: <table id="grid"></table> var data = [[48803, "DSK1", "", "02200220", "OPEN"], [48769, "APPR", "", "77733337", "ENTERED"]]; $("#grid").jqGrid({ datatype: "local", height: 250, colNa ...

Extracting the value of a Json element using the specified Element ID

While delving into JavaScript and the JavaScript framework, I have another query. I am seeking clarity on how to access: { Element: 1 }, { Element: 2},... This contains detailed information about the array. Furthermore, I aim to format it as JSON like s ...

Creating a multipart/form-data POST request in Angular2 and performing validation on the input type File

I am working on sending an image (base64) via a POST request and waiting for the response. The POST request should have a Content-Type of multipart/form-data, and the image itself should be of type image/jpg. This is what the POST request should look like ...

Run JavaScript function when an ajax request encounters an error

When using the ajax function to call a webservice and encountering an error, my goal is to trigger the userCreate() javascript function. $.ajax({ type:"POST", beforeSend: function (request) { request.setRequestHeader("X-DreamFactory-Applic ...

The Three.js GLSL shader encountered a compilation error

I encountered a compile error message: THREE.WebGLShader: Shader could not compile. I attempted to use shaders from shaderfrog.com, but unfortunately they did not compile correctly. To troubleshoot, I added my new vertex and fragment shaders to the DOM a ...

Insert HTML code that is activated when the selection is modified

I have a simple dropdown menu in my HTML code. HTML <select name="breed" onchange="breedChanged()"> <?php while ($row = gdrcd_query($result, 'fetch')){ ?> <option value="<?php echo $row['id_breed']; ?& ...

How can one obtain the object (whether it be a string or an array) named NAME?

Can someone help me create a prototype like this: Array.prototype.getName=function(){ [...]return arrayName; } Then I want to be able to do this: x = new Array; alert(x.name); and have "x" displayed in the alert. I'm currently developing on Chrom ...

Creating an Angular directive that handles asynchronous attribute interpolation

I am facing an issue with my custom directive. In the link function attributes, I am trying to access the value of attributes.user. Here is how the directive is used in my view page: <div my-directive user="{{user.name}}"></div> The user obje ...

What is the best way to showcase all tab content within a single tab menu labeled "ALL"?

I have created a tab menu example below. When you click on the button ALL, it will display all the tabcontent. Each tab content has its own tab menu. Thanks in advance! function openCity(evt, cityName) { var i, tabcontent, tablinks; tabcontent = doc ...

Having trouble getting StencilJS Bottomsheet to work properly? Looking for a way to smoothly slide up your content?

I've been working on creating a Bottomsheet in Stencil, but I'm facing an issue where it shows up suddenly when activated. My goal is to display the overlay when the active property is set, and then smoothly slide up the content. Below is my comp ...