復制代碼 代碼如下:
<?php
/**
* 加密解密類
* 該算法僅支持加密數字。比較適用於數據庫中id字段的加密解密,以及根據數字顯示url的加密。
* @author 深秋的竹子
* @version alpha
* @加密原則 標記長度 + 補位 + 數字替換
* @加密步驟:
* 將a-z,A-Z,0-9 62個字符打亂,取前M(數字最大的位數)位作為 標記長度字符串,取第M+1 到第M+10位為數字替換字符串,剩余的為補位字符串
* 1.計算數字長度n,取亂碼的第n位作為標記長度。
* 2.計算補位的長度,加密串的長度N -1 - n 為補位的長度。根據指定的算法得到補位字符串。
* 3.根據數字替換字符串替換數字,得到數字加密字符串。
* 標記長度字符 + 補位字符串 + 數字加密字符串 = 加密串
* Usage:
* $obj = new XDeode(9);
* $e_txt = $obj->encode(123);
* echo $e_txt.'<br/>';
* echo $key->decode($e_txt);
*/
class XDeode{
private $strbase = "Flpvf70CsakVjqgeWUPXQxSyJizmNH6B1u3b8cAEKwTd54nRtZOMDhoG2YLrI";
private $key,$length,$codelen,$codenums,$codeext;
function __construct($length = 9,$key = 2543.5415412812){
$this->key = $key;
$this->length = $length;
$this->codelen = substr($this->strbase,0,$this->length);
$this->codenums = substr($this->strbase,$this->length,10);
$this->codeext = substr($this->strbase,$this->length + 10);
}
function encode($nums){
$rtn = "";
$numslen = strlen($nums);
//密文第一位標記數字的長度
$begin = substr($this->codelen,$numslen - 1,1);
//密文的擴展位
$extlen = $this->length - $numslen - 1;
$temp = str_replace('.', '', $nums / $this->key);
$temp = substr($temp,-$extlen);
$arrextTemp = str_split($this->codeext);
$arrext = str_split($temp);
foreach ($arrext as $v) {
$rtn .= $arrextTemp[$v];
}
$arrnumsTemp = str_split($this->codenums);
$arrnums = str_split($nums);
foreach ($arrnums as $v) {
$rtn .= $arrnumsTemp[$v];
}
return $begin.$rtn;
}
function decode($code){
$begin = substr($code,0,1);
$rtn = '';
$len = strpos($this->codelen,$begin);
if($len!== false){
$len++;
$arrnums = str_split(substr($code,-$len));
foreach ($arrnums as $v) {
$rtn .= strpos($this->codenums,$v);
}
}
return $rtn;
}
}
/**** 示例 ****/
$begin = 9950;
$end = $begin + 50;
$obj = new XDeode(9);
for($i=$begin;$i<$end;$i++){
$en = $obj->encode($i);
$de = $obj->decode($en);
echoln("[{$i}]=[{$en}]=[{$de}]");
}
function echoln($str){
echo "{$str}<br/>";
}
?>
運行示例結果:
[9950]=[vmizxPPga]=[9950]
[9951]=[vSNSSPPgk]=[9951]
[9952]=[vNQNyPPgV]=[9952]
[9953]=[vyyJJPPgj]=[9953]
[9954]=[vNzQzPPgq]=[9954]
[9955]=[vyNzmPPgg]=[9955]
[9956]=[vXxSNPPge]=[9956]
[9957]=[vXJJJPPgW]=[9957]
[9958]=[vXziQPPgU]=[9958]
[9959]=[viXxSPPgP]=[9959]
[9960]=[vQxmyPPea]=[9960]
[9961]=[viJyJPPek]=[9961]