第一步:先创建一个工具类
<?php
/*
工具类,不涉及第三方php
*/
class UtilClass{
private function keyED($txt,$encrypt_key)
{
$encrypt_key = md5($encrypt_key);
$ctr=0;
$tmp = "";
for($i=0;$i<strlen($txt);$i++)
{
if ($ctr==strlen($encrypt_key))
$ctr=0;
$tmp.= substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1);
$ctr++;
}
return $tmp;
}
/*
加密
*/
public function encrypt($txt,$key)
{
srand((double)microtime()*1000000);
$encrypt_key = md5(rand(0,32000));
$ctr=0;
$tmp = "";
for ($i=0;$i<strlen($txt);$i++)
{
if ($ctr==strlen($encrypt_key))
$ctr=0;
$tmp.=substr($encrypt_key,$ctr,1) . (substr($txt,$i,1) ^ substr($encrypt_key,$ctr,1));
$ctr++;
}
return $this->keyED($tmp,$key);
}
/*加密并用base64编码显示*/
public function encrypt_base64($txt,$key){
return base64_encode($this->encrypt($txt,$key));
}
/*
解密 注:decrypt和encrypt来源于网络
*/
public function decrypt($txt,$key)
{
$txt = $this->keyED($txt,$key);
$tmp = "";
for($i=0;$i<strlen($txt);$i++)
{
$md5 = substr($txt,$i,1);
$i++;
$tmp.= (substr($txt,$i,1) ^ $md5);
}
return $tmp;
}
public function decrypt_base64($txt,$key){
return $this->decrypt(base64_decode($txt),$key);
}
/*获取GUID*/
function GUID(){
return strtoupper(md5(uniqid(mt_rand(), true)));
}
/*格式化GUID*/
function GUID_Format($guid){
$hyphen = chr(45);// "-"
$guid =substr($guid, 0, 8).$hyphen
.substr($guid, 8, 4).$hyphen
.substr($guid,12, 4).$hyphen
.substr($guid,16, 4).$hyphen
.substr($guid,20,12);
return $guid;
}
}
?>
第二步:演示代码调用工具类
<?php
include_once('Techlong/Public/util.class.php');
$util=new UtilClass();
$guid=$util->GUID();
?>
<html>
<head></head>
<body>
GUID值:<?php echo $util->GUID_Format($guid)?>(做为密匙)<br><br>
原值:<input type="text" id="input1_<?php echo $guid ?>" value="<?php $str='12345679'; echo $str; ?>"><br>
密文:<input type="text" id="input2_<?php echo $guid ?>" value="<?php $encryptstr=$util->encrypt($str,$guid); echo $encryptstr; ?>"><br>
解密:<input type="text" id="input3_<?php echo $guid ?>" value="<?php $decryptstr=$util->decrypt($encryptstr,$guid); echo $decryptstr; ?>"><br><br>
密文_base64:<input type="text" size="30" id="input4_<?php echo $guid ?>" value="<?php $encryptstr=$util->encrypt_base64($str,$guid); echo $encryptstr; ?>"><br>
解密:<input type="text" id="input5_<?php echo $guid ?>" value="<?php $decryptstr=$util->decrypt_base64($encryptstr,$guid); echo $decryptstr; ?>"><br>
</body>
<html>
效果: