功能特性
- 對稱加密,同密鑰可加解密
- 支持有效期(秒),過期自動失效返回空串
- 引入隨機密鑰(
$ckey_length),相同明文+密鑰每次產生不同密文,抗彩虹表
- Base64 編碼輸出,安全傳輸
- 內置完整性校驗(MD5 簽名),防篡改
完整函數
function authcode($string, $operation = 'DECODE', $key = '', $expiry = 3600) {
$ckey_length = 4;
$key = md5($key ? $key : 'YOUR_GLOBAL_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));
}
}
使用示例
$key = 'my_secret_key';
// 加密,1 小時有效
$token = authcode('user_id=123&action=login', 'ENCODE', $key, 3600);
// 輸出類似:a1b2XyZ3...(含隨機前綴)
// 解密(1 小時內有效)
$data = authcode($token, 'DECODE', $key);
// 1 小時後返回空字符串
// 永久有效
$perm = authcode('config_data', 'ENCODE', $key, 0);
核心原理解析
- 密鑰派生:
$key → $keya/$keyb 固定部分,$keyc 隨機部分
- 加密載荷結構:
[10位過期時間戳][16位MD5簽名][明文]
- RC4 流加密:
$box S-box 初始化 + 密鑰調度 + 異或加密
- 解密驗證:檢查過期時間 + MD5 簽名,雙重保障
適用場景
- 單點登錄 Token 傳遞
- 臨時下載鏈接、重置密碼鏈接
- API 簽名防重放(配合 nonce)
- 客戶端狀態加密 Cookie
安全提示
- 密鑰 務必保密,建議從環境變量/配置中心讀取
- HTTPS 傳輸防竊聽
- 高安全場景建議改用
openssl_encrypt() (AES-GCM) 或 sodium_crypto_secretbox() (XChaCha20-Poly1305),提供經認證的加密(AEAD)