Home > php教程 > php手册 > body text

收藏一个简洁的PHP可逆加密函数

WBOY
Release: 2016-06-13 09:39:18
Original
988 people have browsed it

很多时候我们需要对数据进行加密解密,比如有些数据需要保存到cookie中,但又不能被用户轻易得到这些数据,这时我们就需要加密这些数据保存到cookie中,等我们需要使用它们的时候再解密。

加密的过程如下:

// 加密数据并写到cookie里
$cookie_data = $this -> encrypt("bkjia", $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)));   
}   
Copy after login

使用的时候再解密:

if( isset($_COOKIE['data']) )
{
	//用cookie给session赋值
	$_SESSION['data'] = decrypt("bkjia", $_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));   
}  
Copy after login

这里记录下这个可逆的加密函数的使用。

Related labels:
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 Recommendations
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!