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

使用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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值