将密钥存入环境变量或专用配置服务,代码中通过 getenv 读取,严禁硬编码在源码或版本控制中。

密钥存储位置与加载机制
使用 .env 文件配合 vlucas/phpdotenv 库管理密钥,确保其不被提交到 Git。

.env 文件应加入 .gitignore。应用启动时加载该文件至环境变量。这种方式解耦了配置与代码,便于在不同环境(开发、测试、生产)切换密钥而不修改代码逻辑。
PHP AES-256-GCM 加密实现
编写一个基于 OpenSSL 的加密类,使用 GCM 模式提供机密性和完整性保护。

<?php
class SecureEncryptor {
private string $key;
private string $method = 'aes-256-gcm';
public function __construct() {
// 从环境变量获取密钥,避免硬编码
$this->key = getenv('ENCRYPTION_KEY');
if (!$this->key) {
throw new RuntimeException('Encryption key not found in environment.');
}
}
public function encrypt(string $plaintext): string {
// 生成随机 IV
$ivLength = openssl_cipher_iv_length($this->method);
$iv = random_bytes($ivLength);
// 执行加密
$ciphertext = openssl_encrypt(
$plaintext,
$this->method,
$this->key,
OPENSSL_RAW_DATA,
$iv,
$tag
);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed.');
}
// 组合 IV 和认证标签以便存储/传输
return base64_encode($iv . $tag . $ciphertext);
}
public function decrypt(string $encryptedData): string {
// 解码并分离 IV、标签和密文
$data = base64_decode($encryptedData);
$ivLength = openssl_cipher_iv_length($this->method);
$iv = substr($data, 0, $ivLength);
$tag = substr($data, $ivLength, 16); // GCM tag is typically 16 bytes
$ciphertext = substr($data, $ivLength + 16);
// 执行解密
$plaintext = openssl_decrypt(
$ciphertext,
$this->method,
$this->key,
OPENSSL_RAW_DATA,
$iv,
$tag
);
if ($plaintext === false) {
throw new RuntimeException('Decryption failed or data tampered.');
}
return $plaintext;
}
}
// 模拟运行
try {
// 假设 ENCRYPTION_KEY 已在环境中设置
$encryptor = new SecureEncryptor();
$secret = "Sensitive Data";
$encrypted = $encryptor->encrypt($secret);
echo "Encrypted: " . $encrypted . PHP_EOL;
$decrypted = $encryptor->decrypt($encrypted);
echo "Decrypted: " . $decrypted . PHP_EOL;
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . PHP_EOL;
}
程序输出包含 Base64 编码的密文和原始明文。若尝试解密被篡改的数据,openssl_decrypt 将返回 false,从而触发异常。这确保了数据的完整性和真实性。
该类封装了密钥获取、随机 IV 生成、加密及解密过程。GCM 模式比 CBC 更安全,因为它内置了认证标签,防止密文被篡改。
IV 重用导致的身份验证失败
当同一密钥重复使用相同的 IV 时,GCM 模式会抛出异常或返回错误。
GCM 要求每个加密操作必须使用唯一的 IV。如果在循环中复用 IV,会导致安全漏洞和程序崩溃。示例代码展示了每次调用都生成新的随机 IV 的正确做法。