PHP 配置文件敏感信息加密保护

```html PHP 配置文件敏感信息加密保护实践

PHP 配置文件敏感信息加密保护实践

在 PHP 应用开发中,数据库密码、API 密钥、JWT 秘钥等敏感信息常存于 .envconfig.php 文件中。若配置文件意外泄露(如 Git 提交、Web 目录误暴露),将导致严重安全风险。本文介绍一种轻量、可靠且符合 PSR 标准的加密保护方案。

核心思路:运行时解密,静态存储加密

不将明文密钥写入配置文件,而是使用对称加密(如 AES-256-CBC)加密敏感字段,并在应用启动时动态解密。密钥(Encryption Key)通过环境变量或系统级密钥管理服务注入,避免硬编码。

代码示例:AES 加密/解密工具类

<?php
// src/Security/ConfigCryptor.php
class ConfigCryptor
{
    private string $cipher = 'AES-256-CBC';
    private string $key;

    public function __construct(string $encryptionKey)
    {
        // 使用 SHA-256 确保密钥长度为 32 字节
        $this->key = hash('sha256', $encryptionKey, true);
    }

    public function encrypt(string $plaintext): string
    {
        $ivlen = openssl_cipher_iv_length($this->cipher);
        $iv = openssl_random_pseudo_bytes($ivlen);
        $ciphertext = openssl_encrypt(
            $plaintext,
            $this->cipher,
            $this->key,
            OPENSSL_RAW_DATA,
            $iv
        );
        return base64_encode($iv . $ciphertext);
    }

    public function decrypt(string $encrypted): string
    {
        $data = base64_decode($encrypted);
        $ivlen = openssl_cipher_iv_length($this->cipher);
        $iv = substr($data, 0, $ivlen);
        $ciphertext = substr($data, $ivlen);
        return openssl_decrypt(
            $ciphertext,
            $this->cipher,
            $this->key,
            OPENSSL_RAW_DATA,
            $iv
        ) ?: '';
    }
}

配置文件与加载逻辑

.env 中存储加密值(可由运维生成):

DB_PASSWORD=U2FsdGVkX1+Z...[base64-encoded]

加载时自动解密:

<?php
// config/database.php
use App\Security\ConfigCryptor;

$encryptKey = $_ENV['APP_ENCRYPTION_KEY'] ?? '';
$cryptor = new ConfigCryptor($encryptKey);

return [
    'host'     => 'localhost',
    'username' => 'app_user',
    'password' => $cryptor->decrypt($_ENV['DB_PASSWORD'] ?? ''),
    'dbname'   => 'myapp',
];
⚠️ 重要安全提示:加密密钥(APP_ENCRYPTION_KEY)必须通过 Docker secrets、Kubernetes Secret、云平台 KMS 或服务器环境变量注入,绝不可写入代码库或配置文件

该方案兼顾安全性与实用性:加密数据静态存储无风险,解密仅发生在内存中;兼容现有配置结构,无需重构框架;且基于 OpenSSL 扩展(PHP 7.1+ 默认启用),无需额外依赖。

进阶建议:结合 symfony/dotenv 实现分环境密钥轮换,并定期审计加密密钥生命周期。安全不是功能,而是贯穿部署与运维的持续实践。

```