PHP可逆加密/解密函数分享
时间:2020-10-17 10:43:24|栏目:PHP代码|点击: 次
函数源码
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);
}
调用函数
$key = 'okyo.cn';
$data = array('id' => 100, 'username' => 'customer', 'password' => 'e10adc3949ba59abbe56e057f20f883e');
$snarr = serialize($data);
$en = encrypt($data, $key);
$de = decrypt($en, $key);
echo "加密原型:";
print_r($data);
echo "
密钥:$key
加密结果:$en
解密结果:";
print_r($de);
复制代码 代码如下:
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);
}
调用函数
复制代码 代码如下:
$key = 'okyo.cn';
$data = array('id' => 100, 'username' => 'customer', 'password' => 'e10adc3949ba59abbe56e057f20f883e');
$snarr = serialize($data);
$en = encrypt($data, $key);
$de = decrypt($en, $key);
echo "加密原型:";
print_r($data);
echo "
密钥:$key
加密结果:$en
解密结果:";
print_r($de);
上一篇:wordpress自定义url参数实现路由功能的代码示例
栏 目:PHP代码
下一篇:php下将XML转换为数组
本文标题:PHP可逆加密/解密函数分享
本文地址:http://www.codeinn.net/misctech/12579.html