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

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

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

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

✅ 核心原则

  • 密钥隔离:密钥绝不硬编码,不存于代码库或 Web 可访问目录
  • 算法合规:优先使用 PHP 7.2+ 原生 openssl_encrypt() / sodium_crypto_secretbox()
  • 环境分级:开发/测试/生产使用独立密钥与配置
  • 审计就绪:所有加解密操作记录日志(脱敏处理)

🔐 安全密钥管理

推荐使用环境变量 + 密钥管理系统(如 HashiCorp Vault 或 AWS KMS)。基础部署示例:
# .env(仅部署时注入,不提交 Git)
ENCRYPTION_KEY=base64:4aX9vZGZqYXNkZmFzZGZhc2RmYXNkZmFzZGZhc2Rm
ENCRYPTION_CIPHER=aes-256-gcm
ENCRYPTION_TAG_LENGTH=16

🛡️ 生产级加密服务类

```php cipher = $_ENV['ENCRYPTION_CIPHER'] ?? 'aes-256-gcm'; $this->tagLength = (int)($_ENV['ENCRYPTION_TAG_LENGTH'] ?? 16); $this->keyLength = match($this->cipher) { 'aes-256-gcm' => 32, default => throw new InvalidArgumentException('Unsupported cipher') }; } public function encrypt(string $plaintext): string { $key = $this->getEncryptionKey(); $iv = random_bytes(12); // GCM recommended IV length $tag = ''; $ciphertext = openssl_encrypt( $plaintext, $this->cipher, $key, OPENSSL_RAW_DATA, $iv, $tag, '', // aad $this->tagLength ); 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); $iv = substr($data, 0, 12); $tag = substr($data, 12, $this->tagLength); $ciphertext = substr($data, 12 + $this->tagLength); $key = $this->getEncryptionKey(); $plaintext = openssl_decrypt( $ciphertext, $this->cipher, $key, OPENSSL_RAW_DATA, $iv, $tag ); if ($plaintext === false) { error_log('[ENCRYPT] Decrypt failed for data length: ' . strlen($encrypted)); throw new RuntimeException('Decryption failed'); } return $plaintext; } private function getEncryptionKey(): string { $raw = $_ENV['ENCRYPTION_KEY'] ?? ''; if (str_starts_with($raw, 'base64:')) { return base64_decode(substr($raw, 7)); } throw new RuntimeException('Invalid ENCRYPTION_KEY format'); } } ```

⚠️ 关键注意事项

切勿使用 mcrypt(已废弃)、md5()/sha1()(非加密哈希)、或自定义 XOR 加密。 生产环境必须启用 openssl 扩展,并通过 php -m | grep openssl 验证。

✅ 部署 checklist

  • ✅ 使用 php-fpm 运行,禁用 allow_url_fopen 和危险函数
  • ✅ Nginx/Apache 配置禁止访问 .envconfig/ 目录
  • ✅ 定期轮换密钥(建议每 90 天),并支持双密钥平滑迁移
  • ✅ 单元测试覆盖加解密边界(空字符串、超长文本、特殊字符)
安全不是功能,而是贯穿设计、部署与运维的持续实践。从今天起,让每一行加密代码都经得起生产考验。 ```