用戶登入後,身份資訊常存於 Cookie(客戶端),但 Cookie 可被竄改,導致偽造登入風險。本文提出兩種實用防護方案:Cookie 資料加密 與 加密 Token 綁定驗證,並提供可直接落地的代碼範例。
採用可逆加密演算法(類 Discuz! authcode),加密後再 Base64 編碼存入 Cookie。偽造者拿到密文也無法在有效期外構造合法密文。
authcodefunction authcode($string, $operation = 'DECODE', $key = '', $expiry = 0) {
$ckey_length = 4;
$key = md5($key ? $key : $GLOBALS['discuz_auth_key']);
$keya = md5(substr($key, 0, 16));
$keyb = md5(substr($key, 16, 16));
$keyc = $ckey_length ? ($operation == 'DECODE' ? substr($string, 0, $ckey_length) : substr(md5(microtime()), -$ckey_length)) : '';
$cryptkey = $keya . md5($keya . $keyc);
$key_length = strlen($cryptkey);
$string = $operation == 'DECODE'
? base64_decode(substr($string, $ckey_length))
: sprintf('%010d', $expiry ? $expiry + time() : 0) . substr(md5($string . $keyb), 0, 16) . $string;
$string_length = strlen($string);
$result = '';
$box = range(0, 255);
$rndkey = array();
for ($i = 0; $i <= 255; $i++) $rndkey[$i] = ord($cryptkey[$i % $key_length]);
for ($j = $i = 0; $i < 256; $i++) {
$j = ($j + $box[$i] + $rndkey[$i]) % 256;
$tmp = $box[$i]; $box[$i] = $box[$j]; $box[$j] = $tmp;
}
for ($a = $j = $i = 0; $i < $string_length; $i++) {
$a = ($a + 1) % 256;
$j = ($j + $box[$a]) % 256;
$tmp = $box[$a]; $box[$a] = $box[$j]; $box[$j] = $tmp;
$result .= chr(ord($string[$i]) ^ ($box[($box[$a] + $box[$j]) % 256]));
}
if ($operation == 'DECODE') {
if ((substr($result, 0, 10) == 0 || substr($result, 0, 10) - time() > 0)
&& substr($result, 10, 16) == substr(md5(substr($result, 26) . $keyb), 0, 16))
return substr($result, 26);
return '';
} else {
return $keyc . str_replace('=', '', base64_encode($result));
}
}
$user = ['uid' => $uid, 'username' => $username];
$user = base64_encode(serialize($user));
$user = authcode($user, 'ENCODE', 'your_secret_key', 0);
setcookie('user', $user, time() + 3600 * 24);
登入時產生 $hash = md5($uid . time()) 存入資料庫(或 Redis/Session),Cookie 同步攜帶 hash 與 hash_expire。驗證時比對資料庫,偽造者無法構造合法 hash。Token 有效期內不更新,過期才重發。
$hash = md5($uid . time());
$hash_expire = time() + 3600 * 24;
$user = ['uid' => $uid, 'username' => $username, 'hash' => $hash];
$user = base64_encode(serialize($user));
setcookie('user', $user, $hash_expire);
// 同步寫入 member 表 hash / hash_expire 欄位
本站專題:php curl用法總結、PHP運算與運算符用法總結、PHP網絡編程技巧總結、php字符串(string)用法總結、php+mysql數據庫操作入門教程 等。