舊版 `mcrypt` 擴充套件已於 PHP 7.2 棄用、PHP 8.0 移除。現代專案請使用 `openssl_encrypt/decrypt`。
<?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";
?>
<?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 | 否 | 不安全、相同明文產生相同密文 | ❌ 禁止使用 |