PHP 配置文件敏感信息加密保护实践
在 PHP 应用开发中,数据库密码、API 密钥、JWT 秘钥等敏感信息常存于 .env 或 config.php 文件中。若配置文件意外泄露(如 Git 提交、Web 目录可访问),将造成严重安全风险。本文介绍一种轻量、可靠且符合 PHP 最佳实践的加密保护方案。
✅ 推荐方案:AES-256-GCM 加密 + 环境密钥分离
使用 PHP 7.1+ 原生 openssl_encrypt() 进行对称加密,采用 AES-256-GCM 模式(提供机密性与完整性校验),密钥由环境变量动态注入,避免硬编码。
🔐 加密工具类示例
<?php
// Security/ConfigCrypt.php
class ConfigCrypt
{
private string $cipher = 'aes-256-gcm';
private int $ivLength;
public function __construct()
{
$this->ivLength = openssl_cipher_iv_length($this->cipher);
}
public function encrypt(string $plaintext, string $key): string
{
$iv = random_bytes($this->ivLength);
$tag = '';
$ciphertext = openssl_encrypt(
$plaintext,
$this->cipher,
$key,
OPENSSL_RAW_DATA,
$iv,
$tag,
'',
16 // GCM auth tag length
);
if ($ciphertext === false) {
throw new RuntimeException('Encryption failed: ' . openssl_error_string());
}
return base64_encode($iv . $tag . $ciphertext);
}
public function decrypt(string $encrypted, string $key): string
{
$data = base64_decode($encrypted);
if (strlen($data) < $this->ivLength + 16) {
throw new RuntimeException('Invalid encrypted data');
}
$iv = substr($data, 0, $this->ivLength);
$tag = substr($data, $this->ivLength, 16);
$ciphertext = substr($data, $this->ivLength + 16);
$plaintext = openssl_decrypt(
$ciphertext,
$this->cipher,
$key,
OPENSSL_RAW_DATA,
$iv,
$tag
);
if ($plaintext === false) {
throw new RuntimeException('Decryption failed: ' . openssl_error_string());
}
return $plaintext;
}
}
📁 安全配置工作流
- 生成主密钥(仅一次):
php -r "echo bin2hex(random_bytes(32));"→ 得到 64 位 hex 字符串 - 设置环境变量(如
.env):
CONFIG_ENCRYPTION_KEY=8a3f...d2e1(⚠️ 不提交至版本库!) - 加密敏感值(部署前):
$crypt = new ConfigCrypt(); echo $crypt->encrypt('my-db-pass', hex2bin($_ENV['CONFIG_ENCRYPTION_KEY'])); - 配置文件中存储密文:
'db_password' => 'base64_encoded_ciphertext_here' - 运行时解密(启动时):
$password = $crypt->decrypt($config['db_password'], hex2bin($_ENV['CONFIG_ENCRYPTION_KEY']));
⚠️ 重要提醒:切勿将加密密钥写入代码或配置文件;始终通过环境变量、Secret Manager 或容器平台注入;定期轮换密钥并重新加密配置。
通过此方案,即使攻击者获取配置文件,也无法直接读取明文凭证。结合 chmod 600 .env、Web 服务器禁止访问配置目录等纵深防御措施,可显著提升应用安全性。
安全不是功能,而是贯穿开发全生命周期的习惯。从第一行配置开始,为你的 PHP 应用筑起第一道加密防线。
```