萬盛學電腦網

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

PHP AES 加密類實現:支援 128/192/256 位、CBC/ECB/CFB/OFB、Base64 輸出

⚠️ 重要前置說明

mcrypt 擴展已於 PHP 7.2 棄用、PHP 8.0 移除。 本文代碼僅供教學/遷移參考。生產環境請使用 openssl_encrypt()/openssl_decrypt() 或 sodium (libsodium) 擴展。

原始類結構(基於 mcrypt)

<?php
class AESMcrypt {
    public $iv = null;
    public $key = null;
    public $bit = 128;
    private $cipher;
    private $mode;

    public function __construct(int $bit, string $key, string $iv, string $mode) {
        if (empty($bit) || empty($key) || empty($iv) || empty($mode)) return null;

        $this->bit  = $bit;
        $this->key  = $key;
        $this->iv   = $iv;
        $this->mode = $mode;

        // 映射位數到 MCRYPT 常數
        $this->cipher = match ($bit) {
            192 => MCRYPT_RIJNDAEL_192,
            256 => MCRYPT_RIJNDAEL_256,
            default => MCRYPT_RIJNDAEL_128,
        };

        // 映射模式
        $this->mode = match (strtolower($mode)) {
            'ecb' => MCRYPT_MODE_ECB,
            'cfb' => MCRYPT_MODE_CFB,
            'ofb' => MCRYPT_MODE_OFB,
            'nofb'=> MCRYPT_MODE_NOFB,
            default => MCRYPT_MODE_CBC,
        };
    }

    public function encrypt(string $data): string {
        return base64_encode(mcrypt_encrypt(
            $this->cipher, $this->key, $data, $this->mode, $this->iv
        ));
    }

    public function decrypt(string $data): string {
        $decrypted = mcrypt_decrypt(
            $this->cipher, $this->key, base64_decode($data), $this->mode, $this->iv
        );
        // 移除 PKCS#7 padding 殘留
        return rtrim(rtrim($decrypted), "\x00..\x1F");
    }
}

// 使用範例
$aes = new AESMcrypt(128, 'abcdef1234567890', '0987654321fedcba', 'cbc');
$cipher = $aes->encrypt('haowei.me');
echo "加密: $cipher\n";
echo "解密: " . $aes->decrypt($cipher) . "\n";

現代替代方案:OpenSSL AES-256-CBC(推薦)

<?php
class AESOpenSSL {
    private string $method;
    private string $key;   // 32 bytes for AES-256
    private string $iv;    // 16 bytes for CBC

    public function __construct(string $key, string $iv = '', string $method = 'AES-256-CBC') {
        // 密鑰派生:建議用 PBKDF2/Argon2,這裡簡單截取/補零
        $this->method = $method;
        $keyLen = (int)($method === 'AES-256-CBC' ? 32 : ($method === 'AES-192-CBC' ? 24 : 16));
        $this->key = substr(hash('sha256', $key, true), 0, $keyLen);
        $this->iv  = strlen($iv) >= 16 ? substr($iv, 0, 16) : str_pad($iv, 16, "\0");
    }

    public function encrypt(string $data): string {
        $cipher = openssl_encrypt($data, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
        if ($cipher === false) throw new Exception('Encryption failed: ' . openssl_error_string());
        return base64_encode($cipher);
    }

    public function decrypt(string $base64Data): string {
        $data = base64_decode($base64Data, true);
        if ($data === false) throw new Exception('Invalid base64');
        $plain = openssl_decrypt($data, $this->method, $this->key, OPENSSL_RAW_DATA, $this->iv);
        if ($plain === false) throw new Exception('Decryption failed: ' . openssl_error_string());
        return $plain;
    }
}

// 使用
$aes = new AESOpenSSL('my-secret-password-123', 'init-vector-1234');
$enc = $aes->encrypt('敏感資料: 信用卡 4242-4242-4242-4242');
echo "加密: $enc\n";
echo "解密: " . $aes->decrypt($enc) . "\n";

關鍵安全實踐

  1. 密鑰管理:永遠不要硬編碼金鑰。使用環境變數、密鑰管理系統(HashiCorp Vault、AWS KMS、Azure Key Vault)。
  2. IV 必須隨機且唯一:CBC 模式下,每次加密生成新 IV(random_bytes(16)),IV 不需保密,但必須與密文一起傳輸/存儲。
  3. 認證加密 (AEAD):優先使用 AES-256-GCM 或 ChaCha20-Poly1305 (libsodium),同時提供機密性與完整性,防止密文篡改。
  4. Padding Oracle 攻擊防護:使用 AEAD 或實現恆定時間解密、統一錯誤訊息。

OpenSSL AEAD 範例(AES-256-GCM)

<?php
function encryptAEAD(string $data, string $key, string $associatedData = ''): string {
    $iv = random_bytes(12); // GCM 建議 12 字節 IV
    $tag = '';
    $cipher = openssl_encrypt($data, 'AES-256-GCM', $key, OPENSSL_RAW_DATA, $iv, $tag, $associatedData);
    if ($cipher === false) throw new Exception('AEAD encrypt failed');
    // 格式:IV (12) + TAG (16) + CIPHERTEXT
    return base64_encode($iv . $tag . $cipher);
}

function decryptAEAD(string $payload, string $key, string $associatedData = ''): string {
    $raw = base64_decode($payload, true);
    if (strlen($raw) < 28) throw new Exception('Invalid payload');
    $iv = substr($raw, 0, 12);
    $tag = substr($raw, 12, 16);
    $cipher = substr($raw, 28);
    $plain = openssl_decrypt($cipher, 'AES-256-GCM', $key, OPENSSL_RAW_DATA, $iv, $tag, $associatedData);
    if ($plain === false) throw new Exception('AEAD decrypt failed: tag mismatch or corruption');
    return $plain;
}

$key = hash('sha256', 'master-key', true); // 32 bytes
$enc = encryptAEAD('機密資料', $key, 'user_id=123');
echo "AEAD 加密: $enc\n";
echo "AEAD 解密: " . decryptAEAD($enc, $key, 'user_id=123') . "\n";

libsodium 方案(最簡單、最安全)

<?php
// PHP 7.2+ 內建 sodium 擴展
$key = sodium_crypto_secretbox_keygen(); // 32 bytes
$nonce = random_bytes(SODIUM_CRYPTO_SECRETBOX_NONCEBYTES); // 24 bytes

$cipher = sodium_crypto_secretbox('極機密內容', $nonce, $key);
// 存儲:nonce + ciphertext (base64)
$stored = base64_encode($nonce . $cipher);

$decoded = base64_decode($stored, true);
$nonce = substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$cipher = substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES);
$plain = sodium_crypto_secretbox_open($cipher, $nonce, $key);
if ($plain === false) throw new Exception('Decryption failed');
echo "解密: $plain\n";

遷移清單:mcrypt_encrypt → openssl_encrypt;MCRYPT_RIJNDAEL_128 → AES-128-CBC;MCRYPT_MODE_CBC → OPENSSL_RAW_DATA + 手動 IV;棄用 ECB 模式(不安全)。

copyright © 萬盛學電腦網 all rights reserved