本文整理自 Discuz! 論壇通行證系統的加密邏輯,封裝為獨立 SysCrypt 類別,採用 動態金鑰 + XOR 位運算 + Base64 編碼 的對稱加密方案,適合 API 簽名、Token 生成、敏感配置加密等場景。非軍用級加密,不可用於密碼儲存 (請用 bcrypt/Argon2)。
<?php
/**
* PHP 加密解密處理類
* 參考:Discuz! 通行證相關函數
* 協議:GPL v2
*/
class SysCrypt {
private string $cryptKey;
public function __construct(string $cryptKey) {
$this->cryptKey = $cryptKey;
}
/**
* 加密
* @param string $plaintext 明文
* @return string Base64 編碼的密文
*/
public function encrypt(string $plaintext): string {
// 1. 生成隨機加密金鑰 (每次加密不同,防止彩虹表)
$encryptKey = md5(mt_rand(0, 32000));
$ctr = 0;
$tmp = '';
// 2. XOR 混淆:明文每字符與 encryptKey 對應字符異或,並夾帶 encryptKey 字符
for ($i = 0; $i < strlen($plaintext); $i++) {
$ctr = ($ctr === strlen($encryptKey)) ? 0 : $ctr;
$tmp .= $encryptKey[$ctr] . ($plaintext[$i] ^ $encryptKey[$ctr++]);
}
// 3. 二次加密:用實例金鑰 ($this->cryptKey) 再次 XOR
return base64_encode($this->xorCrypt($tmp, $this->cryptKey));
}
/**
* 解密
* @param string $ciphertext Base64 密文
* @return string|false 明文或 false (解密失敗)
*/
public function decrypt(string $ciphertext): string|false {
// 1. Base64 解碼
$data = base64_decode($ciphertext, true);
if ($data === false) return false;
// 2. 先用實例金鑰解密
$data = $this->xorCrypt($data, $this->cryptKey);
// 3. 還原明文:跳過夾帶的 encryptKey 字符,XOR 還原
$plaintext = '';
for ($i = 0; $i < strlen($data); $i += 2) {
$keyChar = $data[$i];
$encChar = $data[$i + 1] ?? '';
$plaintext .= $keyChar ^ $encChar;
}
return $plaintext;
}
/**
* 核心 XOR 加密/解密 (對稱操作)
*/
private function xorCrypt(string $data, string $key): string {
$keyLen = strlen($key);
$result = '';
for ($i = 0; $i < strlen($data); $i++) {
$result .= $data[$i] ^ $key[$i % $keyLen];
}
return $result;
}
}
<?php
require 'SysCrypt.php';
// 應用級密鑰 (從環境變數讀取,勿硬編碼)
$crypt = new SysCrypt($_ENV['APP_CRYPT_KEY'] ?? 'default-secret-key-change-me');
// 加密
$plaintext = 'user_id=12345&role=admin&expire=' . (time() + 3600);
$token = $crypt->encrypt($plaintext);
echo "Token: {$token}\n";
// 解密
$decrypted = $crypt->decrypt($token);
if ($decrypted !== false) {
parse_str($decrypted, $params);
print_r($params);
// Array ( [user_id] => 12345 [role] => admin [expire] => 1699900000 )
} else {
echo "解密失敗:Token 損壞或密鑰不符\n";
}
| 層次 | 操作 | 安全作用 | 弱點 |
|---|---|---|---|
| 1. 隨機金鑰 | md5(mt_rand()) | 每次加密產生不同密文 (語義安全性) | mt_rand() 非加密安全隨機源,可預測 |
| 2. XOR 混淆 | 明文 ^ 隨機金鑰字符,並插入金鑰字符 | 隱藏明文統計特徵、增加密文長度 | 已知明文攻擊可還原金鑰流 |
| 3. 二次 XOR | 用固定 $cryptKey 再次 XOR | 綁定應用密鑰,無密鑰無法解密 | 固定金鑰重複使用,多次加密可被差分分析 |
| 4. Base64 | 二進制轉可列印字符 | 傳輸安全 | 無加密強度 |
random_bytes(16) 產生 128-bit 金鑰,bin2hex 或直接用二進制。openssl_encrypt($data, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag),提供機密性、完整性、認證性。APP_CRYPT_KEY 從 Vault/環境變數讀取、定期輪換、分環境隔離。<?php
// 對稱加密 (密鑰 32 bytes)
$key = sodium_crypto_secretbox_keygen(); // 儲存金鑰
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes,每次唯一
$ciphertext = sodium_crypto_secretbox($message, $nonce, $key);
// 儲存: $nonce . $ciphertext (Base64)
$stored = base64_encode($nonce . $ciphertext);
// 解密
$decoded = base64_decode($stored);
$nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$ciphertext = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plaintext = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($plaintext === false) throw new Exception('解密失敗:資料被竄改或金鑰錯誤');
SysCrypt 類別展示了經典 PHP 專案的自定義加密邏輯,理解其原理有助於維護舊系統、遷移數據。但**新專案請直接使用 libsodium (sodium_*) 或 OpenSSL AEAD 模式**,獲得經過密碼學專家審計、硬體加速、抗副通道攻擊的現代加密保護。切記:**密碼儲存永遠用 password_hash()/password_verify() (bcrypt/Argon2),不可加密、不可對稱加密、不可自定義雜湊**。