萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 經典 Authcode 加解密函數修復版:修正 Base64 特殊字元 URL 傳輸問題

Discuz 經典 authcode 函數廣泛用於 Token 生成、驗證碼加密。原版 Base64 輸出包含 +、/、= 等字元,在 URL 參數傳遞時易被轉義導致解密失敗。修復版將這三字元替換為安全替代字串,解密時再還原。

修復版核心邏輯

function authcode(string $string, string $operation = 'DECODE', string $key = '', int $expiry = 0): string {
    // 解碼前先還原安全字元
    if ($operation === 'DECODE') {
        $string = str_replace(['[a]', '[b]', '[c]'], ['+', '&', '/'], $string);
    }

    $ckey_length = 4;
    $key = md5($key ?: 'default_encryption_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 = [];
    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;
        [$box[$i], $box[$j]] = [$box[$j], $box[$i]];
    }
    for ($a = $j = $i = 0; $i < $string_length; $i++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box[$a]) % 256;
        [$box[$a], $box[$j]] = [$box[$j], $box[$a]];
        $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 {
        $ustr = $keyc . str_replace('=', '', base64_encode($result));
        return str_replace(['+', '&', '/'], ['[a]', '[b]', '[c]'], $ustr);
    }
}

使用範例

$token = authcode('user_id=123&action=login', 'ENCODE', 'my_secret_key', 3600);
// 輸出安全字串,可直接放入 URL 參數
$url = "https://example.com/api?token=" . urlencode($token);

// 解碼驗證
$data = authcode($_GET['token'], 'DECODE', 'my_secret_key');
if ($data) {
    parse_str($data, $params);
    // $params['user_id'] = 123, $params['action'] = 'login'
}

安全建議

  • 此演算法為自定義流式加密,未經學術界密碼分析驗證,不建議用於高敏感資料(支付、醫療、身份認證)。
  • 現代專案請使用 openssl_encrypt('aes-256-gcm') 或 sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(PHP 7.2+ / libsodium)。
  • 金鑰管理:使用環境變數或密鑰管理系統(KMS),勿硬編碼。
copyright © 萬盛學電腦網 all rights reserved