Skip to content

PHP 示例代码 ​

覆盖「数据安全」两类密钥的核心场景:

  • 数据对称加密密钥(AES-256-GCM):userSignature 生成、sessionKey 解密
  • 数据签名公私钥(RSASSA-PSS):业务数据签名验签(如 gameSignature)

通用说明 ​

  • AES 部分示例分为两层:
    • AES-256-GCM 工具文件(aes256gcm-util.php):通用对称加解密实现,与 SUD SDK 内部加解密机制保持一致,可直接复用到任意 AES-256-GCM 场景;
    • 业务封装:基于工具文件完成 Payload 构造、字段校验,分别覆盖 userSignature 生成与 sessionKey 解密。
  • AES 字节布局统一为:iv(12) || ciphertext || tag(16),再整体 Base64 编码。
  • RSA 部分(§3 业务数据签名验签)提供独立的 rsa-util.php 工具文件,PSS 参数与 SUD OpenPaaS 服务端签名机制完全一致。
  • 示例仅包含核心逻辑,生产环境需补充日志、异常兜底、监控告警等工程化处理。

环境依赖 ​

  • PHP 7.2+,开启 OpenSSL 扩展(php.ini 中启用 extension=openssl)。
  • RSA 部分(§3)依赖 phpseclib3:composer require phpseclib/phpseclib:~3.0(PHP 原生 OpenSSL 在 7.x 不支持 RSASSA-PSS)。

通用 AES-256-GCM 工具 ​

php
<?php
// aes256gcm-util.php

const AES_ALGORITHM  = 'aes-256-gcm';
const AES_IV_LENGTH  = 12;
const AES_TAG_LENGTH = 16;

function aesEncrypt(string $plaintext, string $keyBase64): string {
    $key = base64_decode($keyBase64, true);
    $iv  = aesGenerateIV();

    $tag = '';
    $cipherBytes = openssl_encrypt(
        $plaintext,
        AES_ALGORITHM,
        $key,
        OPENSSL_RAW_DATA,
        $iv,
        $tag
    );
    if ($cipherBytes === false) {
        throw new RuntimeException('加密失败: ' . openssl_error_string());
    }
    // 与 Java/JCE 一致:iv || ciphertext || tag
    return base64_encode($iv . $cipherBytes . $tag);
}

function aesDecrypt(string $encryptedBase64, string $keyBase64): string {
    $key  = base64_decode($keyBase64, true);
    $data = base64_decode($encryptedBase64, true);

    $iv          = substr($data, 0, AES_IV_LENGTH);
    $tag         = substr($data, -AES_TAG_LENGTH);
    $cipherBytes = substr($data, AES_IV_LENGTH, -AES_TAG_LENGTH);

    $plaintext = openssl_decrypt(
        $cipherBytes,
        AES_ALGORITHM,
        $key,
        OPENSSL_RAW_DATA,
        $iv,
        $tag
    );
    if ($plaintext === false) {
        throw new RuntimeException('解密失败: ' . openssl_error_string());
    }
    return $plaintext;
}

function aesGenerateIV(): string {
    return random_bytes(AES_IV_LENGTH);
}

1. userSignature 生成 ​

基于 aes256gcm-util.php 构造鉴权 Payload 并加密:

php
<?php
// user-signature.php
require_once __DIR__ . '/aes256gcm-util.php';

const SIGNATURE_VERSION = '1';

function generateUserSignature(string $userId, int $expiresAt, string $base64Key): string {
    if ($userId === '') {
        throw new InvalidArgumentException('user_id 不能为空');
    }
    if ($expiresAt <= time()) {
        throw new InvalidArgumentException('expires_at 必须为大于当前时间的 Unix 时间戳(秒)');
    }

    $payload = json_encode([
        'version'    => SIGNATURE_VERSION,
        'user_id'    => $userId,
        'expires_at' => $expiresAt,
    ], JSON_UNESCAPED_UNICODE);
    if ($payload === false) {
        throw new RuntimeException('载荷序列化失败: ' . json_last_error_msg());
    }

    return aesEncrypt($payload, $base64Key);
}

// 调用示例
$base64Key = '你的Base64编码的32字节AES密钥';
$userId    = 'user_123456';
$expiresAt = time() + 24 * 3600;
echo "userSignature: " . generateUserSignature($userId, $expiresAt, $base64Key) . "\n";

2. sessionKey 解密 ​

基于 aes256gcm-util.php 解密并校验载荷字段:

php
<?php
// session-key.php
require_once __DIR__ . '/aes256gcm-util.php';

function decryptSessionKey(string $encryptedSessionKey, string $base64Key, ?string $expectedUserId = null): array {
    $plaintext = aesDecrypt($encryptedSessionKey, $base64Key);

    $payload = json_decode($plaintext, true);
    if (!is_array($payload)) {
        throw new RuntimeException('解密后的载荷不是合法 JSON: ' . json_last_error_msg());
    }

    $userId     = $payload['user_id']     ?? null;
    $sessionKey = $payload['session_key'] ?? null;
    if (empty($userId) || empty($sessionKey)) {
        throw new RuntimeException('载荷缺少必要字段 user_id / session_key');
    }
    if ($expectedUserId !== null && $userId !== $expectedUserId) {
        throw new RuntimeException("user_id 不一致: 期望 {$expectedUserId}, 实际 {$userId}");
    }

    return ['user_id' => $userId, 'session_key' => $sessionKey];
}

// 调用示例
$encryptedSessionKey = 'Base64编码的encrypted_session_key';
$base64Key           = '你的Base64编码的32字节AES密钥';
$expectedUserId      = 'user_123456';
$result = decryptSessionKey($encryptedSessionKey, $base64Key, $expectedUserId);
echo "user_id: {$result['user_id']}, session_key: {$result['session_key']}\n";

3. 业务数据签名验签 ​

基于「数据签名公私钥」对 SUD OpenPaaS 下发的业务数据载荷(如 gameSignature)进行 RSASSA-PSS 验签,PSS 参数为 SHA-256 / MGF1-SHA-256 / salt=32 / trailer=1,签名值以 Base64 编码。

3.1 通用 RSA 签名/验签工具 ​

php
<?php
// rsa-util.php
require_once __DIR__ . '/vendor/autoload.php';

use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;

function rsaSign(string $content, string $privateKeyPem): string {
    $privateKey = PublicKeyLoader::load($privateKeyPem)
        ->withHash('sha256')
        ->withMGFHash('sha256')
        ->withSaltLength(32)
        ->withPadding(RSA::SIGNATURE_PSS);
    return base64_encode($privateKey->sign($content));
}

function rsaVerify(string $content, string $signValueBase64, string $publicKeyPem): bool {
    $publicKey = PublicKeyLoader::load($publicKeyPem)
        ->withHash('sha256')
        ->withMGFHash('sha256')
        ->withSaltLength(32)
        ->withPadding(RSA::SIGNATURE_PSS);
    return $publicKey->verify($content, base64_decode($signValueBase64));
}

3.2 调用示例 ​

php
<?php
// verify-data.php
require_once __DIR__ . '/rsa-util.php';

// $publicKeyPem:从 SUD OpenPaaS 管理后台获取的应用公钥(PEM 字符串)
// $content:     按对应业务文档(如 gameSignature)拼接的"待验签内容"
// $signature:   业务数据载荷中携带的签名值(Base64)
$publicKeyPem = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----";
$content      = '待验签内容';
$signature    = '业务数据中携带的Base64签名值';

if (!rsaVerify($content, $signature, $publicKeyPem)) {
    throw new RuntimeException('数据验签失败,请勿信任该业务数据内容');
}
echo "数据验签通过\n";