萬盛學電腦網

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

PHP 加密解密實用類:基於 AES-256-ECB 與安全 Base64

設計目標

  • 可逆加密:用戶忘記密碼時可找回原文(非單向哈希)。
  • 輸出安全字符:Base64 替換特殊字符(+、/、=),可用於 URL、Cookie、Header。
  • 密鑰派生:用戶提供密鑰 → MD5 生成 32 字節密鑰(AES-256 需 32 字節)。

完整類代碼

<?php
class Crypt {
    private $skey; // 32字節二進制密鑰

    public function __construct($key) {
        // 使用 MD5 將任意長度密鑰固定為 32 字節(二進制)
        $this->skey = hash("md5", $key, true);
    }

    // URL安全的Base64編碼
    public function safe_b64encode($string) {
        $data = base64_encode($string);
        $data = str_replace(array('+', '/', '='), array('-', '_', ''), $data);
        return $data;
    }

    public function safe_b64decode($string) {
        $data = str_replace(array('-', '_'), array('+', '/'), $string);
        $mod4 = strlen($data) % 4;
        if ($mod4) {
            $data .= substr('====', $mod4); // 補齊填充
        }
        return base64_decode($data);
    }

    // 加密
    public function encode($value) {
        if (!$value) return false;
        $text = $value;
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $crypttext = mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->skey, $text, MCRYPT_MODE_ECB, $iv);
        return trim($this->safe_b64encode($crypttext));
    }

    // 解密
    public function decode($value) {
        if (!$value) return false;
        $crypttext = $this->safe_b64decode($value);
        $iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
        $iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
        $decrypttext = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $this->skey, $crypttext, MCRYPT_MODE_ECB, $iv);
        return trim($decrypttext);
    }
}
?>

使用示例

$crypt = new Crypt('my_secret_key_123'); // 密鑰需妥善保管
$plaintext = '敏感信息:用戶密碼123';
$encrypted = $crypt->encode($plaintext);
$decrypted = $crypt->decode($encrypted);

echo "原文: $plaintext\n";
echo "密文: $encrypted\n";
echo "解密: $decrypted\n";
// 輸出:
// 原文: 敏感信息:用戶密碼123
// 密文: x7k9m2... (安全Base64字符串)
// 解密: 敏感信息:用戶密碼123

⚠️ 重要安全警示

  1. mcrypt 擴展已棄用(PHP 7.1)並移除(PHP 7.2)。新項目**必須使用 OpenSSL**(openssl_encrypt/openssl_decrypt)。
  2. ECB 模式不安全:相同明文產生相同密文,洩露模式。生產環境請使用 CBC 或 GCM 模式 並配合隨機 IV。
  3. 密鑰派生過於簡單:MD5 非為密鑰派生設計,應使用 PBKDF2、Argon2 或 HKDF。
  4. 缺乏完整性驗證:需添加 HMAC 或使用認證加密(AEAD,如 AES-GCM)。

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

class ModernCrypt {
    private $key; // 32字節原始密鑰
    private $cipher = 'aes-256-gcm'; // AEAD 模式

    public function __construct($password, $salt = '') {
        // PBKDF2 派生密鑰
        $this->key = hash_pbkdf2('sha256', $password, $salt ?: random_bytes(16), 100000, 32, true);
    }

    public function encrypt($data) {
        $iv = random_bytes(12); // GCM 建議 12 字節 IV
        $tag = '';
        $ciphertext = openssl_encrypt($data, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
        // 組合:IV(12) + TAG(16) + CIPHERTEXT
        return $this->safe_b64encode($iv . $tag . $ciphertext);
    }

    public function decrypt($encoded) {
        $raw = $this->safe_b64decode($encoded);
        $iv = substr($raw, 0, 12);
        $tag = substr($raw, 12, 16);
        $ciphertext = substr($raw, 28);
        $plaintext = openssl_decrypt($ciphertext, $this->cipher, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
        if ($plaintext === false) throw new Exception('解密失敗:數據被篡改或密鑰錯誤');
        return $plaintext;
    }

    // 同樣的 safe_b64encode/decode 方法...
}
copyright © 萬盛學電腦網 all rights reserved