Home  >  Article  >  Backend Development  >  PHP reversible encryption/decryption function example code

PHP reversible encryption/decryption function example code

怪我咯
怪我咯Original
2017-07-13 10:12:421688browse

For most password encryption, we can use md5, sha1 and other methods.

Can effectively prevent data leakage, but these methods are only suitable for data encryption that does not require restoration.

For information that needs to be restored, a reversible encryption and decryption algorithm needs to be used.

The membership system of many projects requires a remember login function. When implementing the function through cookies, since customer information needs to be saved directly to cookies, if the cookie is written directly It will inevitably bring security hidden dangers, so it is relatively safe to save it to cookies after reversible encryption

Function source code

function encrypt($data, $key) { 
$prep_code = serialize($data); 
$block = mcrypt_get_block_size('des', 'ecb'); 
if (($pad = $block - (strlen($prep_code) % $block)) < $block) { 
$prep_code .= str_repeat(chr($pad), $pad); 
} 
$encrypt = mcrypt_encrypt(MCRYPT_DES, $key, $prep_code, MCRYPT_MODE_ECB); 
return base64_encode($encrypt); 
} 

function decrypt($str, $key) { 
$str = base64_decode($str); 
$str = mcrypt_decrypt(MCRYPT_DES, $key, $str, MCRYPT_MODE_ECB); 
$block = mcrypt_get_block_size(&#39;des&#39;, &#39;ecb&#39;); 
$pad = ord($str[($len = strlen($str)) - 1]); 
if ($pad && $pad < $block && preg_match(&#39;/&#39; . chr($pad) . &#39;{&#39; . $pad . &#39;}$/&#39;, $str)) { 
$str = substr($str, 0, strlen($str) - $pad); 
} 
return unserialize($str); 
}

Calling function

$key = &#39;okyo.cn&#39;; 
$data = array(&#39;id&#39; => 100, &#39;username&#39; => &#39;customer&#39;, &#39;password&#39; => &#39;e10adc3949ba59abbe56e057f20f883e&#39;); 
$snarr = serialize($data); 
$en = encrypt($data, $key); 
$de = decrypt($en, $key); 
echo "加密原型:"; 
print_r($data); 
echo " 
密钥:$key 
加密结果:$en 

解密结果:"; 
print_r($de);

The above is the detailed content of PHP reversible encryption/decryption function example code. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn