SG12加密工具配置方法

```html SG12加密工具配置方法(PHP 实战指南)

SG12加密工具配置方法(PHP 实战指南)

SG12 是一款轻量级、面向企业级数据安全的对称加密工具,采用 AES-256-GCM 模式,内置密钥派生(PBKDF2-SHA256)、自动 nonce 管理与完整性校验。本文将手把手演示如何在 PHP 项目中完成 SG12 的安装、初始化与安全配置。

1. 环境准备

确保 PHP ≥ 7.4,启用 opensslmbstring 扩展:

# 检查扩展
php -m | grep -E "openssl|mbstring"

2. 安装 SG12(推荐 Composer 方式)

执行以下命令安装官方维护的封装库:sg12/encryptor

composer require sg12/encryptor:^1.2

3. 基础配置与初始化

SG12 不依赖全局配置文件,所有参数通过 Sg12\Encryptor 构造函数注入,保障环境隔离性:

<?php
require_once 'vendor/autoload.php';

use Sg12\Encryptor;

// ✅ 推荐:从环境变量加载主密钥(避免硬编码)
$masterKey = $_ENV['SG12_MASTER_KEY'] ?? 'your-32-byte-secret-key-here-123456789012';

// 配置选项(全部可选,默认已优化安全参数)
$options = [
    'cipher'     => 'AES-256-GCM',      // 加密算法(固定)
    'key_length' => 32,                 // 密钥长度(字节)
    'iterations' => 600_000,            // PBKDF2 迭代次数(≥10万)
    'salt_size'  => 16,                 // 盐值长度
    'nonce_size' => 12,                 // GCM nonce 长度(推荐12字节)
];

try {
    $sg12 = new Encryptor($masterKey, $options);
    echo "✅ SG12 初始化成功\n";
} catch (Exception $e) {
    throw new RuntimeException("SG12 配置失败:{$e->getMessage()}");
}

4. 加密与解密示例

SG12 自动处理 salt、nonce 和认证标签(auth tag),开发者仅需关注明文与密钥:

// 加密敏感数据
$plaintext = "user_id=1024&token=abc123&exp=1717023600";
$ciphertext = $sg12->encrypt($plaintext);

// 解密(自动验证完整性与防篡改)
$decrypted = $sg12->decrypt($ciphertext);

echo "原文:{$plaintext}\n";
echo "密文(base64):" . base64_encode($ciphertext) . "\n";
echo "解密结果:{$decrypted}\n";
// 输出一致 → 表示配置与加解密链路完整可用
⚠️ 安全提示: • 主密钥 $masterKey 必须通过环境变量或密钥管理服务(如 Vault)注入,严禁写入代码; • 生产环境请将 iterations 设为 ≥500,000 以抵御暴力破解; • 每次 encrypt() 生成唯一 nonce,无需手动管理。

5. 进阶:自定义密钥派生策略

若需多租户场景下按用户动态派生子密钥,可扩展 Encryptor

class TenantEncryptor extends Encryptor
{
    public function encryptForTenant(string $data, string $tenantId): string
    {
        $derivedKey = hash_pbkdf2('sha256', $tenantId, $this->masterKey, 100000, 32, true);
        return $this->encrypt($data, $derivedKey);
    }
}

SG12 的简洁设计让安全不再成为开发负担——正确配置后,即可在登录凭证、API token、数据库字段等场景中零成本启用强加密。

本文基于 SG12 v1.2.3 与 PHP 8.1 编写|文档更新于 2024 年 6 月

```