<?php
class DataEncryptor
{
private string $cipherAlgo;
private string $key;
public function __construct(string $key, string $cipherAlgo = aes-256-gcm)
{
if (empty($key)) {
throw new InvalidArgumentException("Encryption key cannot be empty.");
}
if (!in_array($cipherAlgo, openssl_get_cipher_methods())) {
throw new InvalidArgumentException("Cipher algorithm {$cipherAlgo} is not supported.");
}
$this->key = $key;
$this->cipherAlgo = $cipherAlgo;
}
public function encrypt(string $data): string
{
$ivLen = openssl_cipher_iv_length($this->cipherAlgo);
if ($ivLen === false) {
throw new Exception("Failed to get IV length for {$this->cipherAlgo}.");
}
$iv = openssl_random_pseudo_bytes($ivLen);
if ($iv === false) {
throw new Exception("Failed to generate IV.");
}
$tag = ; // GCM模式需要一個tag
$encryptedData = openssl_encrypt($data, $this->cipherAlgo, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
if ($encryptedData === false) {
throw new Exception("Encryption failed: " . openssl_error_string());
}
// 將IV、加密數據和Tag拼接并進行base64編碼,方便存儲和傳輸
// IV在前,加密數據在中間,Tag在后
return base64_encode($iv . $encryptedData . $tag);
}
public function decrypt(string $encryptedDataBase64): string
{
$decodedData = base64_decode($encryptedDataBase64, true);
if ($decodedData === false) {
throw new Exception("Base64 decoding failed.");
}
$ivLen = openssl_cipher_iv_length($this->cipherAlgo);
if ($ivLen === false) {
throw new Exception("Failed to get IV length for {$this->cipherAlgo}.");
}
// 從解碼后的數據中分離IV、加密數據和Tag
$iv = substr($decodedData, 0, $ivLen);
$tag = substr($decodedData, -16); // GCM模式的Tag通常是16字節
$encryptedData = substr($decodedData, $ivLen, -16);
if (strlen($iv) !== $ivLen) {
throw new Exception("Invalid IV length.");
}
if (strlen($tag) !== 16) { // 假設GCM Tag是16字節
throw new Exception("Invalid Tag length.");
}
$decryptedData = openssl_decrypt($encryptedData, $this->cipherAlgo, $this->key, OPENSSL_RAW_DATA, $iv, $tag);
if ($decryptedData === false) {
throw new Exception("Decryption failed or data was tampered: " . openssl_error_string());
}
return $decryptedData;
}
public static function generateKey(int $length = 32): string
{
$key = openssl_random_pseudo_bytes($length);
if ($key === false) {
throw new Exception("Failed to generate random key.");
}
return $key;
}
}
// 示例使用
try {
// 1. 生成一個安全的密鑰 (在實際應用中,密鑰應該從安全的地方加載,而不是每次運行時生成)
$encryptionKey = DataEncryptor::generateKey(32); // AES-256 需要32字節密鑰
// 假設我們把這個密鑰存儲在一個環境變量中或者安全配置文件里
// $encryptionKey = getenv(APP_ENCRYPTION_KEY);
$encryptor = new DataEncryptor($encryptionKey);
$originalData = "這是一段需要加密的敏感信息,比如用戶的個人資料或支付數據。";
echo "原始數據: " . $originalData . PHP_EOL;
// 2. 加密數據
$encryptedResult = $encryptor->encrypt($originalData);
echo "加密后的數據 (Base64編碼): " . $encryptedResult . PHP_EOL;
// 3. 解密數據
$decryptedResult = $encryptor->decrypt($encryptedResult);
echo "解密后的數據: " . $decryptedResult . PHP_EOL;
// 驗證是否一致
if ($originalData === $decryptedResult) {
echo "加密解密成功,數據一致。" . PHP_EOL;
} else {
echo "加密解密失敗,數據不一致!" . PHP_EOL;
}
// 嘗試篡改數據(模擬攻擊)
echo PHP_EOL . "--- 模擬數據篡改 ---" . PHP_EOL;
$tamperedEncryptedResult = substr($encryptedResult, 0, -5) . AAAAA; // 篡改最后幾個字符
try {
$encryptor->decrypt($tamperedEncryptedResult);
} catch (Exception $e) {
echo "解密篡改數據失敗,符合預期: " . $e->getMessage() . PHP_EOL;
}
} catch (Exception $e) {
echo "錯誤: " . $e->getMessage() . PHP_EOL;
}
// 對于密碼存儲,請使用 password_hash 和 password_verify
echo PHP_EOL . "--- 密碼哈希示例 ---" . PHP_EOL;
$userPassword = "MySecurePassword123";
$hashedPassword = password_hash($userPassword, PASSWORD_BCRYPT); // 使用bcrypt算法
echo "用戶密碼: " . $userPassword . PHP_EOL;
echo "哈希后的密碼: " . $hashedPassword . PHP_EOL;
if (password_verify($userPassword, $hashedPassword)) {
echo "密碼驗證成功。" . PHP_EOL;
} else {
echo "密碼驗證失敗。" . PHP_EOL;
}
// 嘗試錯誤密碼
if (password_verify("WrongPassword", $hashedPassword)) {
echo "錯誤密碼驗證成功 (不應該發生)!" . PHP_EOL;
} else {
echo "錯誤密碼驗證失敗,符合預期。" . PHP_EOL;
}
?>