萬盛學電腦網

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

PHP AES 加密解密完整實作:多種模式、鑰匙長度、Base64/Hex 編碼支援

現代推薦:使用 OpenSSL 擴充套件 (PHP 7.1+)

舊版 `mcrypt` 擴充套件已於 PHP 7.2 棄用、PHP 8.0 移除。現代專案請使用 `openssl_encrypt/decrypt`。

通用 AES 工具類

<?php
class AesCipher {
    private string $method;
    private string $key;
    private string $iv;
    private bool $useBase64;
    
    /**
     * @param string $key 密鑰 (16/24/32 bytes 對應 128/192/256 bits)
     * @param string $iv 初始向量 (16 bytes)
     * @param string $mode 加密模式: cbc, cfb, ofb, ecb, ctr 等
     * @param int $keyBits 鑰匙位數: 128, 192, 256
     * @param bool $useBase64 輸出是否 Base64 編碼
     */
    public function __construct(
        string $key,
        string $iv = '',
        string $mode = 'cbc',
        int $keyBits = 256,
        bool $useBase64 = true
    ) {
        $this->useBase64 = $useBase64;
        
        // 驗證鑰匙長度
        $expectedKeyLen = $keyBits / 8;
        if (strlen($key) !== $expectedKeyLen) {
            // 自動填充或截斷(生產環境建議嚴格檢查)
            $key = substr(hash('sha256', $key, true), 0, $expectedKeyLen);
        }
        $this->key = $key;
        
        // 設定加密方法名稱
        $this->method = "AES-{$keyBits}-" . strtoupper($mode);
        
        // IV 處理
        $ivLen = openssl_cipher_iv_length($this->method);
        if ($ivLen > 0) {
            if ($iv === '') {
                $this->iv = random_bytes($ivLen); // 隨機 IV(加密時使用)
            } else {
                $this->iv = substr($iv, 0, $ivLen);
            }
        } else {
            $this->iv = ''; // ECB 模式不需要 IV
        }
    }
    
    /** 加密 */
    public function encrypt(string $data): string {
        $encrypted = openssl_encrypt(
            $data,
            $this->method,
            $this->key,
            OPENSSL_RAW_DATA,
            $this->iv
        );
        
        if ($encrypted === false) {
            throw new Exception('加密失敗: ' . openssl_error_string());
        }
        
        // 組合 IV + 密文(解密時需分離)
        $output = $this->iv . $encrypted;
        
        return $this->useBase64 ? base64_encode($output) : bin2hex($output);
    }
    
    /** 解密 */
    public function decrypt(string $data): string {
        $raw = $this->useBase64 ? base64_decode($data) : hex2bin($data);
        
        if ($raw === false) throw new Exception('編碼解碼失敗');
        
        $ivLen = openssl_cipher_iv_length($this->method);
        if ($ivLen > 0) {
            $iv = substr($raw, 0, $ivLen);
            $ciphertext = substr($raw, $ivLen);
        } else {
            $iv = '';
            $ciphertext = $raw;
        }
        
        $decrypted = openssl_decrypt(
            $ciphertext,
            $this->method,
            $this->key,
            OPENSSL_RAW_DATA,
            $iv
        );
        
        if ($decrypted === false) {
            throw new Exception('解密失敗: ' . openssl_error_string());
        }
        
        return $decrypted;
    }
    
    /** 靜態工廠:從密碼派生鑰匙 (PBKDF2) */
    public static function fromPassword(string $password, string $salt, int $iterations = 100000, int $keyBits = 256): self {
        $keyLen = $keyBits / 8;
        $key = hash_pbkdf2('sha256', $password, $salt, $iterations, $keyLen, true);
        return new self($key, '', 'cbc', $keyBits);
    }
}

// 使用範例
$key = random_bytes(32); // 256-bit key
$cipher = new AesCipher($key);

$plaintext = '機密資料:信用卡 4242-4242-4242-4242';
$encrypted = $cipher->encrypt($plaintext);
echo "加密: $encrypted\n";

$decrypted = $cipher->decrypt($encrypted);
echo "解密: $decrypted\n";

// 密碼派生鑰匙(適合使用者輸入密碼的場景)
$cipher2 = AesCipher::fromPassword('my-password', 'random-salt-123');
$enc2 = $cipher2->encrypt($plaintext);
echo "密碼派生加密: $enc2\n";
?>

舊版 mcrypt 相容類別(僅供維護舊專案參考)

<?php
/**
 * @deprecated PHP 7.2+ 棄用,請改用 openssl 版本
 */
class LegacyAesMcrypt {
    private $cipher;
    private $mode;
    private $key;
    private $iv;
    
    public function __construct(int $bits, string $key, string $iv, string $mode) {
        $this->key = $key;
        $this->iv = $iv;
        
        $this->cipher = match($bits) {
            192 => MCRYPT_RIJNDAEL_192,
            256 => MCRYPT_RIJNDAEL_256,
            default => MCRYPT_RIJNDAEL_128,
        };
        
        $this->mode = match($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);
        return rtrim($decrypted, "\0..\x1F"); // 移除填充
    }
}
?>

模式選擇指南

模式IV 需求特性適用場景
CBC是 (16 bytes)最常用、需填充、串行處理一般加密、檔案加密
CTR是 (16 bytes)可並行、無填充、可隨機存取大檔案、串流、磁碟加密
GCM是 (12 bytes 推薦)認證加密 (AEAD)、內建完整性驗證高安全需求、API 傳輸、現代標準
ECB否不安全、相同明文產生相同密文❌ 禁止使用

安全性最佳實務

  1. 永遠使用隨機 IV:每次加密生成新 IV,與密文一起儲存。
  2. 鑰匙管理:鑰匙不寫在程式碼,使用環境變數、金鑰管理系統 (KMS/HSM)。
  3. 認證加密:優先選擇 AES-GCM,或加密後計算 HMAC (Encrypt-then-MAC)。
  4. 密碼派生:使用 PBKDF2/Argon2/scrypt 從密碼派生鑰匙,不可直接用密碼當鑰匙。
  5. 時序安全比較:驗證 HMAC 時使用 `hash_equals()`。
copyright © 萬盛學電腦網 all rights reserved