PHP reversible encryption/decryption function sharing_PHP tutorial

WBOY
Release: 2016-07-21 15:15:18
Original
1157 people have browsed it

Function source code

Copy code The code is as follows:

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('des', 'ecb');
$pad = ord($str[($len = strlen($str)) - 1]);
if ($pad && $pad < $block && preg_match('/' . chr($pad) . '{' . $pad . '}$/', $str)) {
$str = substr ($str, 0, strlen($str) - $pad);
}
return unserialize($str);
}

Call function
Copy code The code is as follows:

$key = 'okyo.cn';
$data = array('id' => 100, 'username' => 'customer', 'password' => 'e10adc3949ba59abbe56e057f20f883e');
$snarr = serialize($data);
$en = encrypt($data, $key);
$de = decrypt($en, $key);
echo "Encryption prototype:";
print_r($data);
echo "
Key: $key

Encryption result: $en

Decryption result: ";
print_r($de);

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326127.htmlTechArticleThe function source code copy code is as follows: function encrypt($data, $key) { $prep_code = serialize($data ); $block = mcrypt_get_block_size('des', 'ecb'); if (($pad = $block - (strlen($pr...
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!