php编程中,难免会遇到对数据进行加密与解密的情况,最常用的莫过于加密与加密cookie数据了。
php加密与解密代码:
<?php
// 加密数据并写到cookie里
$cookie_data = $this -> encrypt("nowamagic", $data);
$cookie = array(
'name' => '$data',
'value' => $cookie_data,
'expire' => $user_expire,
'domain' => '',
'path' => '/',
'prefix' => ''
);
$this->input->set_cookie($cookie);
// 加密
public function encrypt($key, $plain_text) {
$plain_text = trim($plain_text);
$iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));
$c_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $plain_text, MCRYPT_ENCRYPT, $iv);
return trim(chop(base64_encode($c_t)));
} //edit www.jb200.com 2013/6/7
//解密
if( isset($_COOKIE['data']) )
{
//用cookie给session赋值
$_SESSION['data'] = decrypt("nowamagic", $_COOKIE['data']);
}
//解决函数
function decrypt($key, $c_t) {
$c_t = trim(chop(base64_decode($c_t)));
$iv = substr(md5($key), 0,mcrypt_get_iv_size (MCRYPT_CAST_256,MCRYPT_MODE_CFB));
$p_t = mcrypt_cfb (MCRYPT_CAST_256, $key, $c_t, MCRYPT_DECRYPT, $iv);
return trim(chop($p_t));
}
?>