When a string that has been encrypted is passed through json_decode, the function may return a

In an effort to protect my database information, I have implemented encryption using simple mcrypt functions for handling JSON data. Here are the functions I've created:

function encrypt($key, $data){
    $encrypted_data = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, $data, MCRYPT_ENCRYPT);
    return base64_encode($encrypted_data);
}

function decrypt($key, $encryptedData){
    $decrypt = mcrypt_cbc(MCRYPT_RIJNDAEL_192, $key, base64_decode($encryptedData), MCRYPT_DECRYPT);
    return $decrypt;
}

After testing the functionality of json_decode without encryption, everything seemed to be working fine. However, upon encrypting and decrypting the data before decoding it with json_decode, I encountered a problem where it only returned NULL.

To pinpoint the issue, I created a simple debugging script as shown below:

include("coreFunctions.php");

$arr = '{"number":"4646464646","type":"home"}';

$key = "ladida";
$locked = encrypt($key, $arr);

var_dump($locked);
var_dump(json_decode(decrypt($key, $locked), true));

Upon verifying that the output of the decryption process is identical to the input, I am puzzled by why this unexpected behavior is occurring.

UPDATE
Further investigation revealed that the length of the data before and after encryption differs. How can I ensure consistency in the data length throughout the encryption process or correct it afterwards?

Answer №1

When using bin2hex, it shows the following output:
033303539222c2274797065223a22686f6d65227d00000000000000000000

This indicates that there are extra null bytes at the end of the decrypted string. This occurs because the mcrybt_cbc operates in blocks. It fills the input and output to multiples of 16 (or 24) bytes to do so. Sometimes, the output may even contain garbage data, which is why most encryption schemes or container formats include a length field.

In this case, you can solve the issue by using rtrim after decryption. Specifically:

 json_decode(rtrim(decrypt($key, $locked), "\0"), true);

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

Contact form malfunctions with problematic Ajax functionality

I am facing issues with my ajax contact form. When I try to submit the form, I receive a "Please fill in all fields" message even though all fields are filled out. Here is my current form code: <form method="get" action="mail.php"> <inp ...

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

An efficient method for extracting data from a JSON array and integrating it into a DataTables display

I am struggling to populate data tables with values from a PHP file that returns JSON responses. Despite receiving the JSON response, I am unable to successfully append the data to the data table. Below is the code snippet used for generating the JSON resp ...

Transform your cURL command to cURL PHP code equivalent

I am new to cURL and AJAX. I have been trying to learn on my own, but I am struggling to figure out how to convert a cURL CMD script into a cURL PHP script. Below is my cURL CMD script: curl 'https://example.url' ^ -H 'authority: example. ...

What is the best way to handle a Symfony 3 service that relies on a variable number of other services?

My experience lies in PHP, but I am fairly new to Symfony. Let's say I have a service that requires an unknown quantity of another service. It is not practical to inject it as I don't know how many instances would be needed. I could potentially u ...

Fetch a restricted set of data from a secondary connection

Here is the structure of my models: Account -> Check -> Result class Account extends Model { public function checks() { return $this->hasMany('App\Check'); } } class Check extends Model { public function results() { retur ...

Retrieving JSON information from a servlet using JavaScript

I am currently facing an issue with parsing JSON data received from my servlet in JavaScript using JQuery. Below is the relevant JavaScript code snippet: $(document).ready(function(){ //alert('document ready'); $('#search-btn').click(f ...

Uploading images simultaneously while filling out a form

Currently, I have a form that requires users to fill it out and upload an image. However, there is a delay of up to 30 seconds when the user hits "Submit" due to the image size being uploaded. I'm interested in finding a way to initiate the image upl ...

Tips for inserting a hyperlink on every row in Vuetables using VUE.JS

Trying to implement a link structure within each row in VUEJS Vuetables has been challenging for me. Despite my research on components and slots, I am struggling to add a link with the desired structure as shown below: <td class="text-center"> <a ...

transferring JSON information from the client to the service

In order to incorporate RESTful architecture into an existing SOAP service, I am modifying the service interface by adding WebGet and WebInvoke attributes. These attributes allow for both REST and SOAP compliant services. Following this CodeProject tutoria ...

How to Create an Alert Message with Title and Dismiss Button in Joomla

After receiving a response from an ajax call, I am trying to display a Joomla notice. Here is the code: $app = JFactory::getApplication(); $app->enqueueMessage('Joomla notice', 'info'); When rendered on the front end, it appears as ...

Convert form data into a JSON object using Vue.js

I'm attempting to generate a JSON object from the submitted form data. Fortunately, I've accomplished this using a variable. However, is there an alternative approach for creating a JSON object? Form <form @submit.prevent="submit"& ...

Tips for incorporating custom blocks into page content while utilizing get_the_content() method

Our Wordpress theme has a custom page template that displays the content from 3 different pages in a tabbed layout. One of these tabs includes a glossary section, which looks like: <div class="glossary-content content e8-tab-panel" data-tab=&q ...

Preserving specific items while juggling multiple tasks

When using a select input with multiple set to true, how can I save this data in a cakephp-friendly way while also implementing validation? <?php echo $this->Form->input("user_id", array('multiple'=> 'checkbox' )); ?> ...

Exploring ways to iterate through an array in JSONATA

Here is an example of an array: { "tocontrol": [{"name": "john"},{"name": "doe"}] } The desired output should look like this: { "method": "OR", "match": [ { &quo ...

PHP Adding Values to a Nested Array

I am encountering some difficulties with retrieving the output from an array. Despite my efforts, I have not been able to determine why each portion of the array is not being assigned a proper index. I even attempted to introduce a counter variable in hope ...

Error: Unexpected data type encountered. Expected an array but found a string instead at line 1, column 2

I have tried multiple suggestions from similar questions but none of them have helped. How can I successfully execute this test? @Test fun isJsonCorrectPersonConvert() { val gson = GsonBuilder().create() val json = gson.toJson("[{\"Id\": ...

Regular expressions are compatible with JavaScript, but unfortunately, they are not supported

After successfully implementing this regex in my JavaScript for webpage validation, I attempted to incorporate it into my PHP script as a backup. However, every string I passed through the regex failed, even correct names. In an effort to resolve the issu ...

When it comes to assigning a background to a div using jQuery and JSON

I have been experimenting with creating a database using only JSON and surprisingly, it worked once I added a "js/" in the URL. However, my current issue lies with CSS. Let me elaborate. Here is the JSON data: [ { "title":"Facebook", ...

Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically und ...