public
Created — forked from baldurrensch/feistel.php

Feistel Hash

  • Download Gist
feistel.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
<?php
/**
* This function computes a hash of an integer. This can be used to not expose values to a customer, such as
* not giving them the id value for passing them to URLs. This algorithm is a bidirectional encryption (Feistel cipher) that maps
* the integer space onto itself.
*
* @link http://wiki.postgresql.org/wiki/Pseudo_encrypt Algorithm used
* @link http://en.wikipedia.org/wiki/Feistel_cipher Wikipedia page about Feistel ciphers
* @param int $value
* @return int
* @author Baldur Rensch <brensch@gmail.com>
*/
function computeHash($value)
{
$l1 = ($value >> 16) & 65535;
$r1 = $value & 65535;
for ($i = 0; $i < 3; $i++) {
$l2 = $r1;
$r2 = $l1 ^ (int) ((((1366 * $r1 + 150889) % 714025) / 714025) * 32767);
$l1 = $l2;
$r1 = $r2;
}
return ($r1 << 16) + $l1;
}
 
// Test Run
 
$numbers = array(
-PHP_INT_MAX,
-56578,
-232,
-34,
-1,
0,
1,
34,
232,
56578,
9999999999,
PHP_INT_MAX,
9999999999999999999999999999, // "0"
);
 
foreach($numbers as $number)
{
print $number . ' = ' . computeHash($number). "\n";
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.