當服務器環境無法安裝 OpenSSL/Mcrypt/Sodium 擴展時,純 PHP 實現的 AES-256 提供兼容標準的加密能力。本實現基於 Chris Veness 的公共領域代碼,遵循 FIPS-197 標準。
<?php
/**
* AES 純 PHP 實現 (AES-128/192/256)
* 來源:Chris Veness 2005-2011, CC-BY 協議
*/
class Aes {
// S-Box 替換盒
private static $sBox = [
0x63,0x7c,0x77,0x7b,0xf2,0x6b,0x6f,0xc5,0x30,0x01,0x67,0x2b,0xfe,0xd7,0xab,0x76,
0xca,0x82,0xc9,0x7d,0xfa,0x59,0x47,0xf0,0xad,0xd4,0xa2,0xaf,0x9c,0xa4,0x72,0xc0,
// ... 完整 256 字節 S-Box (此處省略,完整代碼需包含)
];
// 逆 S-Box
private static $sBoxInv = [ /* 256 字節 */ ];
// 輪常數 Rcon
private static $rcon = [
0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36
];
/** 加密入口:16 字節明文 + 密鑰調度 -> 16 字節密文 */
public static function cipher($input, $w) { /* ... */ }
/** 解密入口 */
public static function decipher($input, $w) { /* ... */ }
/** 密鑰擴展:原始密鑰 -> 輪密鑰調度表 */
public static function keyExpansion($key) { /* ... */ }
// === 內部輪函數 ===
private static function addRoundKey($state, $w, $rnd, $Nb) { /* ... */ }
private static function subBytes($s, $Nb) { /* ... */ }
private static function shiftRows($s, $Nb) { /* ... */ }
private static function mixColumns($s, $Nb) { /* ... */ }
private static function invMixColumns($s, $Nb) { /* ... */ }
// === 輔助:GF(2^8) 乘法 ===
private static function gmul($a, $b) { /* ... */ }
/** 便捷方法:字符串加密 (PKCS7 填充 + CBC 模式 + Base64 輸出) */
public static function encrypt($plaintext, $password, $iv = '') {
// 1. 密鑰派生:PBKDF2 或簡單 SHA256
$key = hash('sha256', $password, true); // 32 字節 = 256 bit
// 2. IV 處理
$iv = $iv ?: openssl_random_pseudo_bytes(16);
// 3. PKCS7 填充
$block = 16;
$pad = $block - (strlen($plaintext) % $block);
$plaintext .= str_repeat(chr($pad), $pad);
// 4. CBC 模式加密
$w = self::keyExpansion($key);
$ciphertext = '';
$prev = $iv;
for ($i = 0; $i < strlen($plaintext); $i += $block) {
$blockData = substr($plaintext, $i, $block);
// XOR IV
for ($j = 0; $j < $block; $j++) $blockData[$j] = $blockData[$j] ^ $prev[$j];
$encrypted = self::cipher(array_map('ord', str_split($blockData)), $w);
$encryptedStr = implode('', array_map('chr', $encrypted));
$ciphertext .= $encryptedStr;
$prev = $encryptedStr;
}
// 5. 組合 IV + 密文並 Base64
return base64_encode($iv . $ciphertext);
}
/** 便捷方法:解密 */
public static function decrypt($ciphertext, $password) {
$data = base64_decode($ciphertext);
$iv = substr($data, 0, 16);
$ciphertext = substr($data, 16);
$key = hash('sha256', $password, true);
$w = self::keyExpansion($key);
$plaintext = '';
$prev = $iv;
for ($i = 0; $i < strlen($ciphertext); $i += 16) {
$block = substr($ciphertext, $i, 16);
$decrypted = self::decipher(array_map('ord', str_split($block)), $w);
$decryptedStr = implode('', array_map('chr', $decrypted));
// XOR IV
for ($j = 0; $j < 16; $j++) $decryptedStr[$j] = $decryptedStr[$j] ^ $prev[$j];
$plaintext .= $decryptedStr;
$prev = $block;
}
// 移除 PKCS7 填充
$pad = ord($plaintext[strlen($plaintext) - 1]);
return substr($plaintext, 0, -$pad);
}
}
?>
<?php
require 'Aes.class.php';
$plaintext = '敏感數據:用戶身份證 110101199003071234';
$password = 'MySuperSecretKey2024!@#'; // 實際應用從安全配置讀取
// 加密
$encrypted = Aes::encrypt($plaintext, $password);
echo "加密結果: $encrypted\n";
// 解密
$decrypted = Aes::decrypt($encrypted, $password);
echo "解密結果: $decrypted\n";
// 驗證
assert($decrypted === $plaintext);
?>
| 維度 | 純 PHP AES | OpenSSL/Sodium 擴展 |
|---|---|---|
| 執行速度 | ~5-10 MB/s (CPU 密集) | ~100-500 MB/s (硬件加速/AES-NI) |
| 側信道攻擊防禦 | 無(時序攻擊風險) | 有(常時間實現) |
| 標準合規性 | 符合 FIPS-197 算法邏輯 | 經過認證、持續更新 |
| 依賴部署 | 零依賴,純 PHP | 需擴展、系統庫 |
| 推薦場景 | 受限環境、教學、低頻加密 | 所有生產環境高頻加密 |
random_bytes(16)),重複 IV 導致語義安全性崩塌<?php
// 現代 PHP (7.1+) 推薦:Sodium (libsodium) - 標準庫、高效、安全
// 安裝:pecl install libsodium 或 PHP 7.2+ 內建
// 加密 (XChaCha20-Poly1305 - 推薦) 或 AES-256-GCM
$key = sodium_crypto_aead_aes256gcm_keygen(); // 或從配置讀取
$nonce = random_bytes(SODIUM_CRYPTO_AEAD_AES256GCM_NPUBBYTES);
$ciphertext = sodium_crypto_aead_aes256gcm_encrypt(
$plaintext, '', $nonce, $key // 附加數據為空
);
// 存儲: nonce + ciphertext (Base64)
// 解密
$plaintext = sodium_crypto_aead_aes256gcm_decrypt(
$ciphertext, '', $nonce, $key
);
?>
純 PHP AES 實現具有教學價值和特定環境適用性,但生產系統必須使用經過專業審計的加密庫(OpenSSL/Sodium),並遵循密鑰管理、IV 生成、認證加密等安全工程實踐。