加密解密类

来源:互联网 发布:oracle安装后怎样编程 编辑:程序博客网 时间:2024/05/01 23:25

 <?php

/**
 *  加密 解密类
 *  加密,可逆
 *  可接受任何字符
 *  安全度非常高
 * 自定义 字符串 和 key
 */
/**
 * 使用示例:
 *$s = new  myCrypt($text);
 *加密
 *echo $string = $s->encrypt();
 *echo "<br>";
 *  解密
 *echo $s->decrypt($string);
 *
 */
class myCrypt
{
/**
* 要加密的字符串
*
* @var string
*/
var $sTxt;
/**
* key 
*
* @var string
*/
var $sKey;
/**
* 定义的加密串码
*
* @var string
*/
var $sChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_."; 
 
/**
* 加密 解密 的key
*
* @var string
*/
var $iKey ="-x6g6ZWm2G9g_vr0Bo.pOq3kRIxsZ6rm3330os";
/**
* 构造函数   
*
* @param string $sTxt
* @param string $sKey
*/
function __construct($sKey = 'anihc ctI')
{
if(empty($sKey))
{
$this->sKey = 'anihc ctI';
}
else
{
$this->sKey = $sKey;
}
}
/**
 * 加密函数
 *
 * @return string
  */
function encrypt($sTxt)
{
$this->sTxt = $sTxt;
$nh1 = rand(0,64);
$nh2 = rand(0,64);
$nh3 = rand(0,64);
$ch1 = $this->sChars{$nh1};
$ch2 = $this->sChars{$nh2};
$ch3 = $this->sChars{$nh3};
$nhnum = $nh1 + $nh2 + $nh3;
$knum = 0;$i = 0;
while(isset($this->sKey{$i}))
{
$knum += ord($this->sKey{$i++});
$mdKey = substr(md5(md5(md5($this->sKey.$ch1).$ch2.$this->iKey).$ch3),$nhnum%8,$knum%8 + 16);
}
$this->sTxt = base64_encode($this->sTxt);
$this->sTxt = str_replace(array('+','/','='),array('-','_','.'),$this->sTxt);
$tmp = '';
$j=0;$k = 0;
$tlen = strlen($this->sTxt);
$klen = strlen($mdKey);
for ($i=0; $i<$tlen; $i++)
{
$k = $k == $klen ? 0 : $k;
$j = ($nhnum+strpos($this->sChars,$this->sTxt{$i})+ord($mdKey{$k++}))%64;
$tmp .= $this->sChars{$j};
}
$tmplen = strlen($tmp);
$tmp = substr_replace($tmp,$ch3,$nh2 % ++$tmplen,0);
$tmp = substr_replace($tmp,$ch2,$nh1 % ++$tmplen,0);
$tmp = substr_replace($tmp,$ch1,$knum % ++$tmplen,0);
return $tmp;
}
 
/**
    * 解密函数
    *
    * @param string $sString  需要解密的字符串
    * @return string
    */
function decrypt($sString)
{
$knum = 0;
$i = 0;
$tlen = strlen($sString);
while(isset($this->sKey{$i}))
{
$knum +=ord($this->sKey{$i++});
}
$ch1 = $sString{$knum % $tlen};
$nh1 = strpos($this->sChars,$ch1);
$sString = substr_replace($sString,'',$knum % $tlen--,1);
$ch2 = $sString{$nh1 % $tlen};
$nh2 = strpos($this->sChars,$ch2);
$sString = substr_replace($sString,'',$nh1 % $tlen--,1);
$ch3 = $sString{$nh2 % $tlen};
$nh3 = strpos($this->sChars,$ch3);
$sString = substr_replace($sString,'',$nh2 % $tlen--,1);
$nhnum = $nh1 + $nh2 + $nh3;
$mdKey = substr(md5(md5(md5($this->sKey.$ch1).$ch2.$this->iKey).$ch3),$nhnum % 8,$knum % 8 + 16);
$tmp = '';
$j=0; $k = 0;
$tlen = strlen($sString);
$klen = strlen($mdKey);
for ($i=0; $i<$tlen; $i++)
{
$k = $k == $klen ? 0 : $k;
$j = strpos($this->sChars,$sString{$i})-$nhnum - ord($mdKey{$k++});
while ($j<0) $j+=64;
$tmp .= $this->sChars{$j};
}
$tmp = str_replace(array('-','_','.'),array('+','/','='),$tmp);
return trim(base64_decode($tmp));
}
}
?>