PHP 加密服务生产环境部署方案

```html PHP 加密服务生产环境部署方案

PHP 加密服务生产环境部署方案

在金融、支付、用户隐私等高敏感场景中,PHP 应用需安全可靠地处理加密操作。本文提供一套兼顾安全性、可维护性与性能的生产级加密服务部署实践。

✅ 核心原则

  • 密钥隔离:密钥绝不硬编码,使用环境变量或专用密钥管理服务(如 HashiCorp Vault)
  • 算法合规:优先选用 PHP 7.2+ 原生支持的 openssl_encrypt() + AES-256-GCM(认证加密)
  • 防御时序攻击:使用 hash_equals() 验证 MAC 或密文完整性
  • 日志脱敏:禁止记录原始密钥、明文密码、解密后敏感数据

🔐 安全加密服务类示例

<?php
class SecureCryptoService
{
    private string $cipher = 'AES-256-GCM';
    private int $keyLength = 32; // 256 bits
    private int $ivLength = 12;   // Recommended for GCM

    public function __construct(private string $key)
    {
        if (mb_strlen($this->key, '8bit') !== $this->keyLength) {
            throw new InvalidArgumentException('Invalid key length');
        }
    }

    public function encrypt(string $plaintext): string
    {
        $iv = random_bytes($this->ivLength);
        $tag = '';
        $ciphertext = openssl_encrypt(
            $plaintext,
            $this->cipher,
            $this->key,
            OPENSSL_RAW_DATA,
            $iv,
            $tag,
            '', // aad (optional)
            16 // 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
    {
        $data = base64_decode($encrypted);
        if ($data === false) {
            throw new InvalidArgumentException('Invalid base64 input');
        }

        $iv = mb_substr($data, 0, $this->ivLength, '8bit');
        $tag = mb_substr($data, $this->ivLength, 16, '8bit');
        $ciphertext = mb_substr($data, $this->ivLength + 16, null, '8bit');

        $plaintext = openssl_decrypt(
            $ciphertext,
            $this->cipher,
            $this->key,
            OPENSSL_RAW_DATA,
            $iv,
            $tag
        );

        if ($plaintext === false) {
            throw new RuntimeException('Decryption failed: ' . openssl_error_string());
        }

        return $plaintext;
    }
}

// 使用示例(生产环境应通过 DI 容器注入)
$service = new SecureCryptoService($_ENV['CRYPTO_KEY'] ?? '');
$encrypted = $service->encrypt('user_token_12345');
echo "Encrypted: {$encrypted}\n";
echo "Decrypted: " . $service->decrypt($encrypted) . "\n";

⚙️ 生产部署关键配置

推荐配置
• Web 服务器启用 HTTPS(强制 TLS 1.2+)
• PHP 启用 openssl 扩展(php -m | grep openssl
• 设置 open_basedir 限制文件访问范围
• 关闭 display_errors,启用 log_errors
⚠️ 严禁行为
× 使用 mcrypt(已废弃)或 md5()/sha1() 加密密码
× 在代码中写死密钥(如 $key = 'my-secret-key';
× 将加密结果存入未加密数据库字段而不校验完整性

🔍 补充建议

对更高安全要求场景,可集成 Halite(基于 libsodium 的现代封装)或对接 AWS KMS / Azure Key Vault 实现密钥生命周期管理。

安全不是功能,而是持续过程 —— 定期审计密钥轮换策略、监控加密失败率、更新 OpenSSL 版本,方能筑牢生产防线。

```