原文提供的 Crypt 類採用 **自製 XOR 流式加密** 配合 md5(rand()) 生成一次性金鑰。雖邏輯可跑通,但**存在嚴重安全缺陷**,**嚴禁用於生產環境敏感資料**:
rand() + microtime() 熵極低,可預測PHP 7.1+ 內建 openssl_encrypt/decrypt 支援 **AES-256-GCM** (Authenticated Encryption with Associated Data) —— **機密性 + 完整性 + 抗重放**,是目前對稱加密的黃金標準。
<?php
declare(strict_types=1);
namespace App\Security;
use RuntimeException;
use SodiumException;
/**
* 現代對稱加密服務:AES-256-GCM (OpenSSL) 或 XChaCha20-Poly1305 (libsodium)
* 提供:機密性、完整性、抗重放、金鑰管理最佳實踐
*/
final class ModernCrypt
{
// 算法常數
private const CIPHER_AES_256_GCM = 'aes-256-gcm';
private const KEY_BYTES = 32; // 256 bits
private const IV_BYTES = 12; // GCM 建議 96 bits (12 bytes)
private const TAG_BYTES = 16; // GCM 標籤 128 bits
// 單例模式或依賴注入均可,此處示範單例
private static ?self $instance = null;
private string $masterKey; // 32 bytes 原始二進制金鑰
private function __construct(string $masterKeyHex)
{
// 驗證金鑰長度:必須 64 個十六進制字符 (32 bytes)
if (strlen($masterKeyHex) !== 64 || !ctype_xdigit($masterKeyHex)) {
throw new RuntimeException('Master key must be 64 hex characters (32 bytes). Generate with: bin2hex(random_bytes(32))');
}
$this->masterKey = hex2bin($masterKeyHex);
}
public static function getInstance(string $masterKeyHex): self
{
if (self::$instance === null) {
self::$instance = new self($masterKeyHex);
}
return self::$instance;
}
/**
* 加密
* @param string $plaintext 明文
* @param string|null $associatedData 關聯資料 (AAD),如用戶 ID、時間戳,加密後不可變,解密時需提供相同值
* @return string Base64 編碼的密文載荷: iv(12) + ciphertext + tag(16)
*/
public function encrypt(string $plaintext, ?string $associatedData = null): string
{
// 1. 生成加密隨機 IV (Nonce)
$iv = random_bytes(self::IV_BYTES);
// 2. 加密
$ciphertext = openssl_encrypt(
$plaintext,
self::CIPHER_AES_256_GCM,
$this->masterKey,
OPENSSL_RAW_DATA, // 輸出原始二進制
$iv,
$tag, // 由引用回傳 GCM 認證標籤
$associatedData ?? '', // AAD
12 // IV 長度 (GCM 模式下 openssl 要求顯式指定)
);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed: ' . openssl_error_string());
}
// 3. 組裝載荷: IV (12) + Ciphertext + TAG (16)
// 解密時按固定長度切割
$payload = $iv . $ciphertext . $tag;
// 4. Base64 編碼便於儲存/傳輸 (JSON、URL、資料庫 TEXT 欄位)
return base64_encode($payload);
}
/**
* 解密
* @param string $payloadBase64 Base64 編碼的密文載荷
* @param string|null $associatedData 必須與加密時完全一致
* @return string 明文
* @throws RuntimeException 驗證失敗、格式錯誤、金鑰錯誤
*/
public function decrypt(string $payloadBase64, ?string $associatedData = null): string
{
$payload = base64_decode($payloadBase64, true); // strict 模式
if ($payload === false) {
throw new RuntimeException('Invalid Base64 payload');
}
$minLen = self::IV_BYTES + self::TAG_BYTES; // 至少 IV + TAG
if (strlen($payload) < $minLen) {
throw new RuntimeException('Payload too short');
}
// 切割固定長度部分
$iv = substr($payload, 0, self::IV_BYTES);
$tag = substr($payload, -self::TAG_BYTES);
$ciphertext = substr($payload, self::IV_BYTES, -self::TAG_BYTES);
// 解密並驗證 TAG (完整性檢查)
$plaintext = openssl_decrypt(
$ciphertext,
self::CIPHER_AES_256_GCM,
$this->masterKey,
OPENSSL_RAW_DATA,
$iv,
$tag,
$associatedData ?? ''
);
if ($plaintext === false) {
// 統一拋出驗證失敗,不洩露具體原因 (防止邊緣通道攻擊)
throw new RuntimeException('Decryption failed: authentication tag mismatch or key error');
}
return $plaintext;
}
/**
* 生成新主金鑰 (僅供部署/輪換時使用)
*/
public static function generateMasterKey(): string
{
return bin2hex(random_bytes(self::KEY_BYTES));
}
}
// ==================== 使用示範 ====================
// 1. 生成主金鑰 (僅執行一次,存入 .env 或密鑰管理系統)
// $masterKey = ModernCrypt::generateMasterKey();
// echo "MASTER_KEY=$masterKey\n";
// 輸出範例: MASTER_KEY=a1b2c3d4e5f6... (64 hex chars)
// 2. 實際應用
// $_ENV['MASTER_KEY'] 從環境變數讀取,絕不寫死代碼庫
$crypt = ModernCrypt::getInstance($_ENV['MASTER_KEY'] ?? '');
// 加密敏感資料 (如 API Token、個人資訊)
$apiToken = 'sk_live_abcdef1234567890';
$encrypted = $crypt->encrypt($apiToken, 'user_12345'); // AAD 綁定用戶 ID
echo "Encrypted: $encrypted\n";
// 解密
try {
$decrypted = $crypt->decrypt($encrypted, 'user_12345');
echo "Decrypted: $decrypted\n"; // sk_live_abcdef1234567890
} catch (RuntimeException $e) {
echo "解密失敗: " . $e->getMessage(); // 竄改、金鑰錯誤、AAD 不符
}
// 嘗試竄改密文 (修改 1 byte)
$tampered = substr_replace($encrypted, 'X', 10, 1);
try {
$crypt->decrypt($tampered, 'user_12345');
} catch (RuntimeException $e) {
echo "竄改檢測成功: " . $e->getMessage(); // Decryption failed...
}
?>
| 特性 | 實作細節 | 安全意義 |
|---|---|---|
| 算法 | AES-256-GCM (AEAD) | 機密性+完整性+認證,單次操作完成,無填充攻擊風險 |
| 金鑰管理 | 32 bytes 隨機主金鑰,Hex 儲存環境變數,絕不硬編碼 | 防止代碼洩露導致金鑰洩露,支援金鑰輪換 |
| IV (Nonce) | random_bytes(12) 每次加密唯一隨機 | GCM 要求 IV **絕不重複**,隨機 96 bits 碰撞機率可忽略 |
| 認證標籤 (TAG) | 16 bytes GCM 標籤,隨密文儲存,解密時強制驗證 | 任何密文竄改、AAD 不符、金鑰錯誤均導致解密失敗 |
| 關聯資料 (AAD) | 加密/解密雙方需提供相同字串 (如 user_id, timestamp) | 綁定業務上下文,防止密文在不同語境間移花接木 |
| 載荷格式 | IV(12) || Ciphertext || TAG(16) → Base64 | 固定長度切割無歧義,Base64 安全存儲傳輸 |
| 錯誤處理 | 統一拋出 RuntimeException,不洩露具體失敗原因 | 防止時序攻擊、邊緣通道洩露 |
若伺服器安裝 ext-sodium,**XChaCha20-Poly1305** 更現代、更快、抗邊緣通道、Nonce 可 24 bytes 隨機無壓力:
<?php
if (extension_loaded('sodium')) {
// 加密
$key = sodium_hex2bin($masterKeyHex); // 32 bytes
$nonce = random_bytes(SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES); // 24 bytes
$ciphertext = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
$plaintext,
$associatedData ?? '',
$nonce,
$key
);
// 載荷: nonce(24) + ciphertext(+tag)
$payload = base64_encode($nonce . $ciphertext);
// 解密
$payload = base64_decode($payload, true);
$nonce = substr($payload, 0, 24);
$ciphertext = substr($payload, 24);
$plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
$ciphertext,
$associatedData ?? '',
$nonce,
$key
);
if ($plaintext === false) throw new RuntimeException('Decryption failed');
}
?>
**拒絕自製加密,擁抱標準庫**。PHP 內建 openssl_encrypt (AES-256-GCM) 與 sodium_* (XChaCha20-Poly1305) 提供了工業級、經過嚴格密碼學審計的對稱加密能力。本文提供的 ModernCrypt 類封裝了金鑰管理、IV 生成、載荷序列化、AAD 綁定、錯誤統一等最佳實踐,**可直接投入生產環境**保護 API Token、個人隱私、支付憑證等高敏感資料。