WEB交互安全一直是個各大網站的首要解決方案,本文介紹的PHP加密類非常實用哦,帶有公鑰,這是最大的亮點,沒有公鑰是不能解密的,加密度非常高。
類代碼:
<?php
/**
* PHP加密類
* 瓊台博客
*/
class Jiami{
// 公鑰
protected $key = 'lee';
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=''){
if(empty($key)){
$key=$this->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);
}
public function decrypt($txt,$key=''){
if(empty($key)){
$key=$this->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 setKey($key){
if(empty($key)){
return null;
}
$this->key=$key;
}
public function getPK(){
return $this->key;
}
}
使用方法:
<?php
// 先包含加密類
require_once('jiami.class.php');
// 要加密的字符串
$string = 'http://www.bkjia.com';
// 實例化加密類
$jiami= new Jiami();
// 設置公鑰
$jiami->setKey('qttc');
// 加密字符串
$enc = $jiami->encrypt($string,$jiami->getPK());
// 解密字符串
$dec = $jiami->decrypt($enc,$jiami->getPK());
echo '<meta charset="utf-8" />';
echo '加密前 : '.$string .'<br/>';
echo '加密後 : '.$enc .'<br/>';
echo '解密後 : '.$dec;
?>
頁面執行結果
結果1:

結果2:

由以上結果可以看到,每次加密產生的加密字符串都不一樣,這是隨機的。
解密的時候,需要使用加密時的公鑰,否則無法解密。如你這邊加密公鑰使用‘qttc',解密的時候,也需要使用這個'qttc'作為公鑰去解密,否則無法解密。
對稱加密加密速度比非對稱加密快,對稱加密密鑰不能公開而非對稱的私鑰必須保密公鑰可以公開,關於管理和發布對稱加密比較復雜,關於算法對稱加密通常用DES,AES,IDEA。非對稱用RSA
C.加密密鑰和解密密鑰匙相同的