大家都知道用戶登陸后,用戶信息一般會選擇保存在cookie里面,因為cookie是保存客戶端,并且cookie可以在客戶端用瀏覽器自由更改,這樣將會造成用戶cookie存在偽造的危險,從而可能使偽造cookie者登錄任意用戶的賬戶。下面就說說平常一些防止用戶登錄cookie信息安全的方法:一、cookie信息加密法cookie信息加密法即用一種加密方法,加密用戶信息,然后在存入cookie,這樣偽造者即使得到cookie也只能在cookie有效期內對這個cookie利用,無法另外偽造cookie信息。
這里附上一個加密函數:
<!--?phpfunction authcode($string, $Operation = 'DECODE', $key = '', $expiry = 0) { // 動態密匙長度,相同的明文會生成不同密文就是依靠動態密匙 $ckey_length = 4; // 密匙 $key = md5($key ? $key : $GLOBALS['discuz_auth_key']); // 密匙a會參與加解密 $keya = md5(substr($key, 0, 16)); // 密匙b會用來做數據完整性驗證 $keyb = md5(substr($key, 16, 16)); // 密匙c用于變化生成的密文 $keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length): substr(md5(microtime()), -$ckey_length)) : ''; // 參與運算的密匙 $cryptkey = $keya.md5($keya.$keyc); $key_length = strlen($cryptkey); // 明文,前10位用來保存時間戳,解密時驗證數據有效性,10到26位用來保存$keyb(密匙b), //解密時會通過這個密匙驗證數據完整性 // 如果是解碼的話,會從第$ckey_length位開始,因為密文前$ckey_length位保存 動態密匙,以保證解密正確 $string = $operation == 'DECODE' ? base64_decode(substr($string, $ckey_length)) : s這樣當設置用戶信息的cookie時,就無法對其進行偽造:
<!--?php$user = array("uid"=-->$uid,"username"=>$username);$user = base64_encode(serialize($user));$user = authcode($user,'ENCODE','www.phpskill.com',0); //加密 setcookie("user",$user,time()+3600*24);?>二、用加密令牌對cookie進行保護
$hash = md5($uid.time());//加密令牌值$hash_expire =time()+3600*24;//加密令牌值為一天有效期$user = array("uid"=>$uid,"username"=>$username,"hash"=>$hash);$user = base64_encode(serialize($user));setcookie("user",$user,$hash_expr);然后把$hash和$hash_expire 存入member表中hash和hash_expire對應字段中,也可以存入nosql,session用戶偽造cookie時,hash無法偽造,偽造的hash和數據庫中的不一致用戶每次登陸,這個hash_expire有效期內不更新hash值,過期則更新php純技術交流群: 323899029
原文轉載于:http://www.phpskill.com/html/show-1-4424-1.html
新聞熱點
疑難解答