首頁  >  文章  >  後端開發  >  分享一段php加密解密的程式碼

分享一段php加密解密的程式碼

怪我咯
怪我咯原創
2017-07-16 11:03:271735瀏覽

專案中有時我們需要使用PHP將特定的資訊加密,也就是透過加密演算法產生一個加密字串#,這個加密後的字串可以透過解密演算法進行解密,以便於程式對解密後的資訊進行處理。
最常見的應用在使用者登入以及一些API資料交換的場景。

最常見的應用程式在使用者登入以及一些API資料交換的場景。
筆者收錄了一些比較經典的PHP加密解密函數程式碼,分享給大家。加密解密原理一般都是透過一定的加密解密演算法,將金鑰加入演算法中,最後得到加密解密結果。

<?php  
$key = "This is supposed to be a secret key !!!";  

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;  
}  

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 keyED($tmp,$key);  
}  

function decrypt($txt,$key)  
{  
$txt = 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;  
}  

$string = "Hello World !!!";  

// encrypt $string, and store it in $enc_text  
$enc_text = encrypt($string,$key);  

// decrypt the encrypted text $enc_text, and store it in $dec_text  
$dec_text = decrypt($enc_text,$key);  

print "Original text : $string <Br>\n";  
print "Encrypted text : $enc_text <Br>\n";  
print "Decrypted text : $dec_text <Br>\n";  
?>

以上是分享一段php加密解密的程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn