Skip to content

Instantly share code, notes, and snippets.

@baldurrensch
Created September 12, 2012 22:58
  • Star 3 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save baldurrensch/3710618 to your computer and use it in GitHub Desktop.
Feistel Hash
<?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>
*/
private static 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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment