Skip to content

Instantly share code, notes, and snippets.

@ammarfaizi2
Last active April 19, 2018 16:05
Show Gist options
  • Save ammarfaizi2/7aece54e96eb86a0df347fef7e407faa to your computer and use it in GitHub Desktop.
Save ammarfaizi2/7aece54e96eb86a0df347fef7e407faa to your computer and use it in GitHub Desktop.
<?php
/**
* @author Ammar Faizi <[email protected]>
* @license MIT
*/
/**
* @param string $str
* @param string $key
* @param bool $binarySafe
* @return string
*/
function encrypt($str, $key, $binarySafe = true)
{
$key = (string) $key;
$salt = makeSalt();
$key = sha1($key.$salt);
$klen = strlen($key);
$slen = strlen($str);
$k = $klen - 1;
$j = 0;
$h = $slen - 1;
$r = "";
for ($i=0; $i < $slen; $i++) {
$r .= chr(
ord($str[$i]) ^ ($pps = ord($key[$j])) ^ ($cost = ord($key[$k])) ^ ($i | (($k & $j) ^ $h)) ^ (($i + $k + $j + $h) % 2) ^ ($cost % 2) ^ ($pps ^ 2) ^ (($pps + $cost) % 3) ^ (abs(~$cost + $pps) % 2)
);
$j++;
$k--;
$h--;
if ($j === $klen) {
$j = 0;
}
if ($k === -1) {
$k = $klen - 1;
}
if ($h === 0) {
$h = $slen - 1;
}
}
return $binarySafe ? strrev(base64_encode($r.$salt)) : $r.$salt;
}
function makeSalt()
{
$r = "";
for ($i=0; $i < 5; $i++) {
$r .= chr(rand(1, 255));
}
return $r;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment