How to Encrypt & Decrypt Order of Array in Php
I want to encrypt order with key in Php. I mean i have an array like this:
$arr=[5,"a","li",10];
$key="random";
$newOrder=encryptArr($arr,$key); // [10,"li",5,"a"]
$original=decryptArr($newOrder,$key); //[5,"a","li",10]
Solution 1:
We can achieve expected result by implementing our own shuffle, that uses random numbers derived from a predetermined seed, generated from our key.
function encryptArr(array $input, string $key): array
{
$seed = makeSeed($key);
$swaps = generateSwaps(count($input), $seed);
return swapElements($input, $swaps);
}
function decryptArr(array $input, string $key): array
{
$seed = makeSeed($key);
$swaps = generateSwaps(count($input), $seed);
// If we used the same seed when "encrypting",
// then all we have to do is swap the shuffled array in reverse order.
$swaps = array_reverse($swaps);
return swapElements($input, $swaps);
}
/**
* Helper function that converts string key into an int
* by calculating crc32 polynomial from the string
*/
function makeSeed(string $key): int
{
return crc32($key);
}
/**
* We are using a predetermined $seed to generate a pairs of random numbers from 0 to $length-1
* Eg. [[0, 0], [1, 3], [2, 3], [3, 3]]
*
*/
function generateSwaps(int $length, int $seed): array
{
$swaps = [];
for ($i = 0; $i < $length; $i++) {
mt_srand($seed+$i);
$random_index = mt_rand(0, $length-1);
$swaps[] = [$i, $random_index];
}
return $swaps;
}
function swapElements(array $input, array $swaps): array
{
foreach ($swaps as $swap) {
$tmp = $input[$swap[0]];
$input[$swap[0]] = $input[$swap[1]];
$input[$swap[1]] = $tmp;
}
return $input;
}
$arr=[5,"a","li",10];
$key="test";
$newOrder=encryptArr($arr,$key);
print_r($newOrder);
$original=decryptArr($newOrder,$key);
print_r($original);
Output
Array
(
[0] => 5
[1] => 10
[2] => a
[3] => li
)
Array
(
[0] => 5
[1] => a
[2] => li
[3] => 10
)