Olivier - 3 months ago 14
Javascript Question

# How to reverse an algorithm using modulo and bitwise XOR operators on a JavaScript array?

``````var alphaNumbersStr = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
var hexaString      = '0123456789abcdef';
var str32           = '4af27d7ef70b1263da25022af735508b';
var str             = 'FoooooBar';

var arr = [];
for (var i = 0; i < str.length; i++) {
}
// --
// Start : arr ==> [ 31, 14, 14, 14, 14, 14, 27, 0, 17 ]
// --
for (var i = 0; i < 10000; i++) {

arr[i % str.length] += hexaString.indexOf(str32.charAt(i % 32)) ^ arr[(i + 1) % str.length] ^ arr[(i + 2) % str.length];

if (arr[i % str.length] > alphaNumbersStr.length - 1) {
}
}
// --
// End : after 10000 iterations : arr ==> [ 38, 8, 32, 4, 18, 24, 2, 48, 22 ]
// --
``````

Given the following snippet, I'm trying to reverse this algorithm so that I could return to the original array state (step 0).

Any idea on how this could be solved?

Just do all steps backwards. The operations performed are in such a way that the modulo operation is possible to revert.

``````function revert(arr) {
for (let i = 9999; i >= 0; i--) {
//we know this as these values didnt get affected this iteration
let added = hexaString.indexOf(str32.charAt(i % 32)) ^ arr[(i + 1) % str.length] ^ arr[(i + 2) % str.length];

//the important difference in modulo

//single overflow is what we need to predict
//if we went over, we went smaller again
let overflow = modadd > arr[i % str.length];

//we need to undo the modulo
if (overflow) {
let diff = modadd - arr[i % str.length];
arr[i % str.length] = alphaNumbersStr.length - diff;
}
//Not much to do otherwise
else arr[i % str.length] -= modadd;
}
return arr;
}

//Just so it can be run
``````Value of <code>arr</code>:&nbsp;&nbsp;<input onblur="change()" id="a" size="50" value="[31, 14, 14, 14, 14, 14, 27, 0, 17]">