Certain keys may cause the failure of String XOR encryption

Trying to "encrypt" a JavaScript string with PHP and then decode it using JavaScript.

The PHP function for encryption:

function xor_string( $text, $xorKey ) {
    $xored = '';
    $chars = str_split( $text );

    $i = 0;

    while ( $i < count( $chars ) ) {
        $xored .= chr( ord( $chars[$i] ) ^ $xorKey );
        $i++;
    }

    return $xored;
}

The JavaScript decryption function:

function xor_string( str, key ) {
    var xored = "";
    for (i=0; i<str.length;i++) {
        var a = str.charCodeAt(i);
        var b = a ^ key;
        xored = xored+String.fromCharCode(b);
    }
    console.log(xored);
}

This method works with certain keys but fails with others. For example:

echo urlencode( xor_string( 'document.location.href.search', 67 ) );

Returns:

%27%2C+6.%26-7m%2F%2C+%227%2A%2C-m%2B1%26%25m0%26%221+%2B

When attempting to "decode" it with JavaScript using:

var str = decodeURIComponent("%27%2C+6.%26-7m%2F%2C+%227%2A%2C-m%2B1%26%25m0%26%221+%2B");
xor_string( str, 67 );

The result is:

dohument.lohation.href.searhh

Unsure why this inconsistency is occurring. Has anyone encountered this issue before?

Works well with some "keys" like 120, but encounters failures with many others.

Answer №1

A timeless favorite :-)

When comparing PHP's urlencode with JavaScript's encodeURIComonent, it's important to note that they handle spaces differently; one uses +, while the other uses %20.

To address this discrepancy, tools like phpjs provide a PHP-compatible decodeURI function.

> var phpstring = "%27%2C+6.%26-7m%2F%2C+%227%2A%2C-m%2B1%26%25m0%26%221+%2B";
> xor_string(decodeURIComponent(phpstring.replace(/\+/g, "%20")), 67 );
"document.location.href.search"

It's worth noting that the issue only arises with characters encoded as spaces by your xor function (and its parameter).

Answer №2

An improved approach would be to utilize rawurlencode() over urleconde().

When using rawurlencode(), a space will be converted to '%20', whereas urlencode() converts it to '+'. '%20' is the expected format for a space in decodeURIComponent().

Check out the complete example below:

<?php
    function xor_string( $text, $xorKey ) {
    $xored = '';
    $chars = str_split( $text );
    $i = 0;
    while ( $i < count( $chars ) ) {
        $xored .= chr( ord( $chars[$i] ) ^ $xorKey );
        $i++;
    }
    return $xored;
    }
?><html>
<body>
Encoded (php):
<div id="phpUrlEncode">
<?=urlencode( xor_string( 'document.location.href.search', 67 ) )?>
</div>
<div id="phpRawUrlEncode">
<?=rawurlencode( xor_string( 'document.location.href.search', 67 ) )?>
</div>
<br />
Decoded (js):
<div id="jsDecodeUrl"></div>
<div id="jsDecodeRawUrl"></div>
<script type="text/javascript">
function decodeStr(rawId,displayId) {
    var raw = document.getElementById(rawId).innerHTML;
    document.getElementById(displayId).innerHTML = xor_string(decodeURIComponent(raw),67);
}

function xor_string( str, key ) {
    var xored = "";
    for (i=0; i<str.length;i++) {
        var a = str.charCodeAt(i);
        var b = a ^ key;
        xored = xored+String.fromCharCode(b);
    }
    //console.log(xored);
    return xored;
}

decodeStr('phpUrlEncode','jsDecodeUrl');
decodeStr('phpRawUrlEncode','jsDecodeRawUrl');
</script>
</body>
</html>

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

Obtain the information from a JSONP-formatted dataset

Just when I think I have mastered identifying an element in an object, I come across a situation where I am unable to obtain the desired value. This part is successful and the data returned is accurate: A map click triggers the function MapClick(queryResu ...

Error occurred in AngularJS service due to incorrect data type

Looking to store the URL of a query in an AngularJS service like this: var mortgageloanService = angular.module('loanstreetIpadAppApp', []); mortgageloanService.factory('updateTable', function($http) { return { getParams: fun ...

Menu Slide – Inability to close by clicking div in specific section

I am attempting to create a slide menu that (a) opens, displaying a white faded overlay over the rest of the page and (b) closes when I click a link in the menu or anywhere on the white overlay. (a) Opening the menu works correctly. (b) However, I am enc ...

The implementation of jQuery show/hide functionality for a div based on select change is not functioning properly when the

Currently, I am streamlining an HTML web form by using scripts to populate select box options. While the show/hide functionality works perfectly for one select with hardcoded options, it fails for a dropdown filled via script and JSON data. Can anyone pinp ...

JQuery Form Validation - Detecting Input Changes

Currently, I have a form set up with jQuery validation that works well, but I want to enhance its functionality. The form uses a plugin for validation, but it only checks for errors upon submission. I'm interested in finding a way to validate the fiel ...

Generating Typescript sourcemaps with Babel through the command line

I'm struggling to figure out how to generate sourcemaps with Babel when using the command line. The Babel documentation seems to focus more on integrating with gulp, and it's not clear how to apply that knowledge to the command line. Currently, ...

Executing a controller method in Grails using JavaScript

When working in a Grails view, I find myself needing to execute a JavaScript method to retrieve certain information. To achieve this, I have set up a submit action as shown below: <input type="submit" name="submit" class="submit action-button" value="G ...

Transforming a div into a clickable hyperlink

I have a JavaScript function that generates a div with a link inside it. Here is how the div and link are created: $('#info').find('#link').text("View"); //Creates a new link var eventLink1 = document.createElement('a& ...

Is it possible to retrieve information from a JSON file using Vue.js 2?

Looking to retrieve data from a JSON file with the json data format. [{"id":81,"body":"There are some reason to fix the issues","created_at":"2017-11-16 11:56:47","updated_at":"2017-11-16 11:56:47"}] I have integrated vue-resource and followed the Vue sy ...

Using Three.js to display a PerspectiveCamera with a visible bounding Sphere

My challenge is to create a Scene that loads a single .obj file where the object is fully visible in the PerspectiveCamera upon scene initialization. The field of view (FOV) is set at 60 The objects vary in size TrackballControls are utilized for camera ...

Sending an object using multipart formData with request in node.js: A step-by-step guide

I'm having trouble with a POST request using request. Every time I try to include the to object in the formData, I encounter an error. var fs = require('fs'); var request = require('request'); var file = './test/asset ...

Error: Incorrect Path for Dynamic Import

Recently, I've been trying to dynamically load locale files based on the locale code provided by Next.js. Unfortunately, every time I attempt a dynamic import, an error surfaces and it seems like the import path is incorrect: Unable to load translatio ...

Parse JSON files from a folder and concatenate them to a CSV using Node.js

Thank you for offering your help. I have a collection of JSON files located in a directory with unknown names. I need help with the following: (1) Reading all the JSON files (2) Appending the data from the JSON files to output.csv (3) Adding "-Appended" t ...

While using Ckeditor, typing or deleting text will cause an input checkbox to become unchecked and its value to be altered

Whenever I try to make any changes or use the backspace key in Ckeditor, the checkbox gets unchecked and the value resets to 0. Despite my efforts, I have been unable to find a solution to this issue. How can I resolve this problem? CKEDITOR.replace( &ap ...

Is it possible for me to access information from an external URL using JSON?

As I delve into learning about JSON for app development, I've encountered an issue with a JSON and PHP-based chat system. While the code functions properly for the same origin policy, when it comes to sending and receiving data from an external URL, i ...

Using External APIs in React: A Guide

Recently, I created a React app using the npm module 'create-react-app' I ran into an issue where I needed to call an external API from api.example.com, but found that Axios was making requests to localhost instead of the external API. Here is ...

When I utilized Ajax to modify the arrangement of a table, I found that my other jQuery functionalities associated with the table were not being triggered

I implemented Ajax functionality to dynamically change the order of a table by clicking on the headings in the first row. However, there seems to be an issue where after clicking on a heading and then on a cell in the last two columns, the alert is not tri ...

What is the best way to refresh the DOM following an Ajax request using jQuery?

Is there a way to dynamically update the DOM with newly added records after making a call? Should I fetch the new database record content in the callback function and then append it using jQuery? Please provide guidance if there is insufficient data to a ...

Differences in how line breaks are handled in script output have been observed when comparing Atom and Notepad

Currently, I am utilizing a small script that generates a .txt file and inputs some data into it. Strangely, when I open the .txt file in Atom, the content appears on separate lines as I intended. However, when I access the same file in notepad, all the co ...

angularjs potentially unsafe:data warning appears when taking a screenshot using html2canvas

While using angularjs and html2canvas for capturing a screenshot, I have encountered some issues. The screenshot captures successfully on some screens, but not on others. I am getting the following error: https://i.sstatic.net/FVNym.png I have tried to re ...