PHP加密解密 第2章 lock PHP加密解密 第2章 lock

2023-06-15

函数

function lockUrl($txt, $key='lulublog'): string
{
   $txt = $txt.$key;
   $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
   $nh = rand(0,64);
   $ch = $chars[$nh];
   $mdKey = md5($key.$ch);
   $mdKey = substr($mdKey,$nh%8, $nh%8+7);
   $txt = base64_encode($txt);
   $tmp = '';
   $k = 0;
   for ($i=0; $i < strlen($txt); $i++) {
       $k = $k == strlen($mdKey) ? 0 : $k;
       $j = ($nh+strpos($chars,$txt[$i])+ord($mdKey[$k++]))%64;
       $tmp .= $chars[$j];
   }
   return base64_encode($ch.$tmp);
}

function unlockUrl($txt, $key='lulublog'): string
{
   $txt = base64_decode($txt);
   $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-=+";
   $ch = $txt[0];
   $nh = strpos($chars,$ch);
   $mdKey = md5($key.$ch);
   $mdKey = substr($mdKey,$nh%8, $nh%8+7);
   $txt = substr($txt,1);
   $tmp = '';
   $k = 0;
   for ($i=0; $i < strlen($txt); $i++) {
       $k = $k == strlen($mdKey) ? 0 : $k;
       $j = strpos($chars,$txt[$i])-$nh - ord($mdKey[$k++]);
       while ($j<0) $j+=64;
       $tmp .= $chars[$j];
   }
   return trim(base64_decode($tmp),$key);
}

测试

$lockUrl = lockUrl('14');
var_dump($lockUrl);
$unlockUrl = unlockUrl($lockUrl);
var_dump($unlockUrl);

注意:加密只能是数字

阅读 467