PHP双密加密保护方案

```html PHP双密加密保护方案:安全与可控的双重保障

PHP双密加密保护方案:安全与可控的双重保障

在敏感数据(如用户身份证号、银行卡号、API密钥)的存储与传输中,单一密钥加密存在明显风险:密钥泄露即全盘失守。为此,我们提出**PHP双密加密保护方案**——通过“业务密钥 + 系统主密钥”两级协同加密,实现密钥分离、权限隔离与动态轮换能力。 该方案并非标准算法,而是一种**工程化安全设计模式**:数据先用随机生成的业务密钥(Data Key)加密,再用系统级主密钥(Master Key)加密该业务密钥,最终将加密后的数据与加密后的业务密钥一并存储。解密时需双重授权,显著提升攻击成本。

核心优势

  • 密钥分离:业务密钥仅单次有效,主密钥不接触明文数据
  • 权限控制:可为不同模块分配独立业务密钥,主密钥由安全中心统一管理
  • 灵活轮换:仅重加密业务密钥即可完成主密钥更新,无需迁移全部密文

PHP 实现示例(基于 OpenSSL AES-256-GCM)

<?php
class DualKeyEncryptor
{
    private string $masterKey;

    public function __construct(string $masterKey)
    {
        // 主密钥建议从环境变量或KMS获取,长度不足则SHA256补足
        $this->masterKey = hash('sha256', $masterKey, true);
    }

    public function encrypt(string $plaintext): array
    {
        // Step 1: 生成随机业务密钥(32字节)和IV
        $dataKey = random_bytes(32);
        $iv = random_bytes(12); // GCM推荐12字节IV

        // Step 2: 用业务密钥加密明文(AES-256-GCM)
        $ciphertext = openssl_encrypt(
            $plaintext,
            'aes-256-gcm',
            $dataKey,
            OPENSSL_RAW_DATA,
            $iv,
            $authTag,
            '',
            16 // AEAD tag长度
        );

        if ($ciphertext === false) {
            throw new RuntimeException('加密失败: ' . openssl_error_string());
        }

        // Step 3: 用主密钥加密业务密钥(同样AES-GCM,新IV)
        $keyIv = random_bytes(12);
        $encryptedDataKey = openssl_encrypt(
            $dataKey,
            'aes-256-gcm',
            $this->masterKey,
            OPENSSL_RAW_DATA,
            $keyIv,
            $keyAuthTag,
            '',
            16
        );

        return [
            'ciphertext' => base64_encode($ciphertext),
            'auth_tag'   => base64_encode($authTag),
            'iv'         => base64_encode($iv),
            'encrypted_data_key' => base64_encode($encryptedDataKey),
            'key_iv'     => base64_encode($keyIv),
            'key_auth_tag' => base64_encode($keyAuthTag),
        ];
    }

    public function decrypt(array $payload): string
    {
        // 解密业务密钥
        $dataKey = openssl_decrypt(
            base64_decode($payload['encrypted_data_key']),
            'aes-256-gcm',
            $this->masterKey,
            OPENSSL_RAW_DATA,
            base64_decode($payload['key_iv']),
            base64_decode($payload['key_auth_tag'])
        );

        if ($dataKey === false) {
            throw new RuntimeException('业务密钥解密失败');
        }

        // 用业务密钥解密数据
        $plaintext = openssl_decrypt(
            base64_decode($payload['ciphertext']),
            'aes-256-gcm',
            $dataKey,
            OPENSSL_RAW_DATA,
            base64_decode($payload['iv']),
            base64_decode($payload['auth_tag'])
        );

        if ($plaintext === false) {
            throw new RuntimeException('数据解密失败');
        }

        return $plaintext;
    }
}

// 使用示例
$encryptor = new DualKeyEncryptor($_ENV['MASTER_KEY'] ?? 'your-secure-master-key-here');
$secret = 'ID123456789|2025-12-31';

try {
    $encrypted = $encryptor->encrypt($secret);
    echo "密文:\n" . json_encode($encrypted, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT) . "\n";

    $decrypted = $encryptor->decrypt($encrypted);
    echo "解密成功: {$decrypted}\n"; // 输出: ID123456789|2025-12-31
} catch (Exception $e) {
    error_log("双密操作异常: " . $e->getMessage());
}
?>
安全提醒:生产环境中请勿硬编码主密钥;建议结合 Hashicorp Vault、AWS KMS 或自建密钥管理服务;所有密钥操作应在可信容器/安全模块内执行;定期审计密钥生命周期。
双密方案不追求“绝对不可破”,而是以合理成本构建纵深防御体系。在 PHP 应用中落地该模式,既兼容现有架构,又为数据安全增加关键一道锁。记住:加密不是终点,而是安全治理的新起点。 ```