自己封装的加密cookie相关函数

PHP开发 | 2014-04-11 17:02:27 | 阅读 1871 次 | 评论(0)

使用mcrypt对cookie值进行可逆加密,浏览器端存储的是加密过得值,可以当session用。


//配置部分
$config['cookie_prefix'] = 'bccn_';
$config['cookie_domain'] = 'bccn.net';
$config['cookie_path'] = '/';
$config['cookie_skey'] = 'jewhdfy234957632946w32trweyugtfrhsdgfa';

//实现函数部分
function set_cookie($key, $value, $expire=2400, $secure=false, $httponly=true){
	global $config;
	$key = $config['cookie_prefix'] . $key;
	$value = encrypt($value, $config['cookie_skey']);
	setcookie($key, $value, time()+$expire, $config['cookie_path'], $config['cookie_domain'], $secure, $httponly);
}

function get_cookie($key){
	global $config;
	$key = $config['cookie_prefix'] . $key;
	if(array_key_exists($key, $_COOKIE)){
		return decrypt($_COOKIE[$key], $config['cookie_skey']);
	}else{
		return '';
	}
}

function del_cookie($key){
	global $config;
	$key = $config['cookie_prefix'] . $key;
	if(array_key_exists($key, $_COOKIE)){
		setcookie($key, '', time()-3600, $config['cookie_path'], $config['cookie_domain'], false, false);
	}
}

//加密解密函数
function encrypt($str, $skey){
	$skey = substr($skey, 0, 56);
	$td = mcrypt_module_open('blowfish-compat', '', 'ecb', '');
	$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	mcrypt_generic_init($td, $skey, $iv);
	$encrypted_str = mcrypt_generic($td, $str);
	mcrypt_generic_deinit($td);
	mcrypt_module_close($td);
	$encrypted_str = bin2hex($encrypted_str);
	return $encrypted_str;
}

function decrypt($str, $skey){
	$str = hex2bin($str);
	$skey = substr($skey, 0, 56);
	$td = mcrypt_module_open('blowfish-compat', '', 'ecb', '');
	$iv = mcrypt_create_iv (mcrypt_enc_get_iv_size($td), MCRYPT_RAND);
	mcrypt_generic_init($td, $skey, $iv);
	$decrypted_str = mdecrypt_generic($td, $str);
	mcrypt_generic_deinit($td);
	mcrypt_module_close($td);
	return $decrypted_str;
}

//测试
set_cookie('test', 'hello world! 哈哈');
//del_cookie('test');
echo get_cookie('test');

文章评论,共0条
游客请输入验证码
浏览1921552次
文章归档
最新评论
  • Miss_Zou:不都是复制粘贴的吗
  • Miss_Zou:目测是大佬
  • 神犇dengyuhy:语文很好