萬盛學電腦網

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

PHP Mcrypt 擴展庫加密解密實戰:AES/RIJNDAEL-128 CBC 模式詳解

前言

注意:Mcrypt 擴展已於 PHP 7.2 棄用,PHP 8.0 完全移除。現代項目請使用 OpenSSL 或 Sodium (libsodium)。本文僅供維護舊代碼參考,新項目請跳過。

Mcrypt 算法概覽

Mcrypt 2.4.7 提供 22 種算法,常用對稱加密算法:

  • RIJNDAEL-128 (AES):目前最推薦,安全性高、性能好、國際標準
  • TripleDES (3DES):舊系統相容,密鑰長度 168 位,速度較慢
  • Blowfish:可變密鑰長度,適合軟件加密
  • Twofish / Serpent:AES 競爭者,安全性高但較少用

安裝配置 (舊版 PHP)

# 編譯安裝 libmcrypt
wget ftp://argeas.cs-net.gr/pub/unix/mcrypt/libmcrypt-2.5.8.tar.gz
tar -xzf libmcrypt-2.5.8.tar.gz
cd libmcrypt-2.5.8
./configure --disable-posix-threads
make && make install

# PHP 編譯時啟用
./configure --with-mcrypt=/usr/local [其他選項]
make && make install

Windows 下啟用 extension=php_mcrypt.dll 並確保 libmcrypt.dll 在 PATH 中。

核心加密解密代碼 (AES-128-CBC)

<?php
/**
 * Mcrypt AES-128-CBC 加密解密演示
 * 注意:PHP 7.2+ 棄用,8.0+ 移除,新項目請用 OpenSSL
 */
class McryptLegacy
{
    private string $cipher = MCRYPT_RIJNDAEL_128; // AES-128
    private string $mode = MCRYPT_MODE_CBC;
    private string $key;
    private int $keySize;
    private int $ivSize;

    public function __construct(string $key) {
        // 密鑰長度必須匹配算法要求:RIJNDAEL-128 需 16/24/32 字節 (128/192/256 位)
        $this->keySize = mcrypt_get_key_size($this->cipher, $this->mode); // 16
        $this->ivSize = mcrypt_get_iv_size($this->cipher, $this->mode);   // 16
        
        // 密鑰派生:簡單截取/補零,生產環境請用 PBKDF2
        $this->key = substr(hash('sha256', $key, true), 0, $this->keySize);
    }

    /** 加密:返回 Base64 編碼的 密文(含 IV 前綴) */
    public function encrypt(string $plaintext): string {
        // 生成隨機 IV
        $iv = mcrypt_create_iv($this->ivSize, MCRYPT_DEV_URANDOM);
        
        // 加密(需手動 PKCS#7 填充,Mcrypt 不自動填充)
        $padded = $this->pkcs7Pad($plaintext);
        $ciphertext = mcrypt_encrypt($this->cipher, $this->key, $padded, $this->mode, $iv);
        
        // IV + 密文 組合並 Base64
        return base64_encode($iv . $ciphertext);
    }

    /** 解密:輸入 Base64 編碼的 IV+密文 */
    public function decrypt(string $encoded): string {
        $data = base64_decode($encoded, true);
        if ($data === false || strlen($data) < $this->ivSize) {
            throw new InvalidArgumentException('無效的加密數據');
        }
        
        // 提取 IV 與密文
        $iv = substr($data, 0, $this->ivSize);
        $ciphertext = substr($data, $this->ivSize);
        
        $padded = mcrypt_decrypt($this->cipher, $this->key, $ciphertext, $this->mode, $iv);
        return $this->pkcs7Unpad($padded);
    }

    /** PKCS#7 填充 */
    private function pkcs7Pad(string $data): string {
        $pad = $this->ivSize - (strlen($data) % $this->ivSize);
        return $data . str_repeat(chr($pad), $pad);
    }

    /** PKCS#7 去填充 */
    private function pkcs7Unpad(string $data): string {
        $pad = ord($data[strlen($data) - 1]);
        if ($pad < 1 || $pad > $this->ivSize) {
            throw new RuntimeException('填充數據無效,可能密鑰錯誤或數據損壞');
        }
        return substr($data, 0, -$pad);
    }
}

// 使用示例
$key = 'Four score and twenty years ago'; // 實際應從安全配置讀取
$crypto = new McryptLegacy($key);

$original = 'Applied Cryptography, by Bruce Schneier, is a wonderful cryptography reference.';
echo "原文:$original\n";

$encrypted = $crypto->encrypt($original);
echo "加密:$encrypted\n";

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

assert($original === $decrypted, '加解密不一致');

關鍵安全細節

1. IV (初始化向量) 必須隨機且唯一

  • CBC 模式下,相同明文 + 相同 Key + 相同 IV → 相同密文(洩露模式)
  • 每次加密生成新隨機 IV,與密文一起存储(通常作為前綴)
  • 使用 MCRYPT_DEV_URANDOM 而非 MCRYPT_RAND

2. 密鑰管理

  • **永不硬編碼密鑰**,使用環境變量、密鑰管理服務(HashiCorp Vault、AWS KMS)
  • 密鑰應由高熵隨機源生成,非用戶密碼直接使用
  • 生產環境採用 PBKDF2/Argon2/scrypt 從密碼派生密鑰

3. 完整性驗證 (防篡改)

Mcrypt 僅提供機密性,**無完整性保護**。攻擊者可修改密文導致解密後明文被控制。必須添加 HMAC:

// 加密時
$hmac = hash_hmac('sha256', $iv . $ciphertext, $hmacKey, true);
$final = base64_encode($iv . $ciphertext . $hmac);

// 解密時先驗證 HMAC,再解密

現代替代方案:OpenSSL (PHP 7.1+)

class AesGcmCrypto
{
    private string $key;
    private int $keyLen = 32; // AES-256
    private int $ivLen = 12;  // GCM 推薦 12 字節 IV
    private int $tagLen = 16; // 認證標籤長度

    public function __construct(string $key) {
        $this->key = hash('sha256', $key, true); // 32 字節
    }

    public function encrypt(string $plaintext, string $aad = ''): string {
        $iv = random_bytes($this->ivLen);
        $ciphertext = openssl_encrypt($plaintext, 'aes-256-gcm', $this->key, OPENSSL_RAW_DATA, $iv, $tag, $aad);
        if ($ciphertext === false) throw new RuntimeException('加密失敗');
        // IV(12) + 密文 + TAG(16)
        return base64_encode($iv . $ciphertext . $tag);
    }

    public function decrypt(string $encoded, string $aad = ''): string {
        $data = base64_decode($encoded, true);
        if ($data === false || strlen($data) < $this->ivLen + $this->tagLen) {
            throw new InvalidArgumentException('無效數據');
        }
        $iv = substr($data, 0, $this->ivLen);
        $tag = substr($data, -$this->tagLen);
        $ciphertext = substr($data, $this->ivLen, -$this->tagLen);
        
        $plaintext = openssl_decrypt($ciphertext, 'aes-256-gcm', $this->key, OPENSSL_RAW_DATA, $iv, $tag, $aad);
        if ($plaintext === false) throw new RuntimeException('解密失敗:認證標籤驗證失敗,數據可能被篡改');
        return $plaintext;
    }
}

遷移清單 (Mcrypt → OpenSSL)

  1. 替換 mcrypt_* 為 openssl_encrypt/decrypt
  2. 算法名稱映射:MCRYPT_RIJNDAEL_128 + MCRYPT_MODE_CBC → 'aes-128-cbc' (或 'aes-256-gcm' 推薦)
  3. IV 長度:AES 固定 16 字節 (CBC) / 12 字節 (GCM)
  4. 填充:OpenSSL 自動處理 PKCS#7,無需手動填充
  5. **強烈建議升級至 AES-GCM**,獲得認證加密 (AEAD),同時保證機密性與完整性
  6. 重新加密所有存量密文(雙寫遷移或離線批量轉換)

總結

Mcrypt 曾是 PHP 加密主流選擇,但已成為歷史。舊項目維護時需注意 IV 隨機性、密鑰派生、填充處理、完整性驗證四大塊。新項目**直接使用 OpenSSL AES-GCM 或 Sodium crypto_secretbox**,享受現代密碼學最佳實踐與長期維護保障。

copyright © 萬盛學電腦網 all rights reserved