Skip to content

PHP Example Code ​

Covers the core scenarios of the two types of "data security" keys:

  • Data symmetric encryption key (AES-256-GCM): userSignature generation, sessionKey decryption
  • Data signature public/private key (RSASSA-PSS): business data signature verification (e.g., gameSignature)

General Notes ​

  • The AES part of the example is split into two layers:
    • AES-256-GCM utility file (aes256gcm-util.php): a general-purpose symmetric encryption/decryption implementation, consistent with the internal encryption/decryption mechanism of the SUD SDK, and directly reusable in any AES-256-GCM scenario;
    • Business wrapper: builds on the utility file to perform Payload construction and field validation, covering userSignature generation and sessionKey decryption respectively.
  • The AES byte layout is uniformly: iv(12) || ciphertext || tag(16), then Base64-encoded as a whole.
  • The RSA part (§3 Business data signature verification) provides an independent rsa-util.php utility file, whose PSS parameters are fully consistent with the SUD OpenPaaS server-side signing mechanism.
  • The example contains only the core logic; production environments need to add logging, exception fallbacks, monitoring alerts, and other engineering measures.

Environment Dependencies ​

  • PHP 7.2+, with the OpenSSL extension enabled (enable extension=openssl in php.ini).
  • The RSA part (§3) relies on phpseclib3: composer require phpseclib/phpseclib:~3.0 (PHP's native OpenSSL does not support RSASSA-PSS in 7.x).

General AES-256-GCM Utility ​

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('encryption failed: ' . openssl_error_string());
    }
    // Consistent with 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('decryption failed: ' . openssl_error_string());
    }
    return $plaintext;
}

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

1. userSignature Generation ​

Build the authentication Payload based on aes256gcm-util.php and encrypt it:

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 must not be empty');
    }
    if ($expiresAt <= time()) {
        throw new InvalidArgumentException('expires_at must be a Unix timestamp (seconds) greater than the current time');
    }

    $payload = json_encode([
        'version'    => SIGNATURE_VERSION,
        'user_id'    => $userId,
        'expires_at' => $expiresAt,
    ], JSON_UNESCAPED_UNICODE);
    if ($payload === false) {
        throw new RuntimeException('payload serialization failed: ' . json_last_error_msg());
    }

    return aesEncrypt($payload, $base64Key);
}

// Invocation example
$base64Key = 'Your Base64-encoded 32-byte AES key';
$userId    = 'user_123456';
$expiresAt = time() + 24 * 3600;
echo "userSignature: " . generateUserSignature($userId, $expiresAt, $base64Key) . "\n";

2. sessionKey Decryption ​

Decrypt based on aes256gcm-util.php and validate the payload fields:

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('The decrypted payload is not valid JSON: ' . json_last_error_msg());
    }

    $userId     = $payload['user_id']     ?? null;
    $sessionKey = $payload['session_key'] ?? null;
    if (empty($userId) || empty($sessionKey)) {
        throw new RuntimeException('payload missing required fields user_id / session_key');
    }
    if ($expectedUserId !== null && $userId !== $expectedUserId) {
        throw new RuntimeException("user_id mismatch: expected {$expectedUserId}, actual {$userId}");
    }

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

// Invocation example
$encryptedSessionKey = 'Base64-encoded encrypted_session_key';
$base64Key           = 'Your Base64-encoded 32-byte AES key';
$expectedUserId      = 'user_123456';
$result = decryptSessionKey($encryptedSessionKey, $base64Key, $expectedUserId);
echo "user_id: {$result['user_id']}, session_key: {$result['session_key']}\n";

3. Business Data Signature Verification ​

Based on the "data signature public/private key", perform RSASSA-PSS signature verification on the business data payload delivered by SUD OpenPaaS (such as gameSignature). The PSS parameters are SHA-256 / MGF1-SHA-256 / salt=32 / trailer=1, and the signature value is Base64-encoded.

3.1 General RSA Signing/Verification Utility ​

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 Invocation Example ​

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

// $publicKeyPem: the application public key obtained from the SUD OpenPaaS admin console (PEM string)
// $content:      the "content to be verified" concatenated per the corresponding business documentation (e.g., gameSignature)
// $signature:    the signature value carried in the business data payload (Base64)
$publicKeyPem = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----";
$content      = 'content to be verified';
$signature    = 'the Base64 signature value carried in the business data';

if (!rsaVerify($content, $signature, $publicKeyPem)) {
    throw new RuntimeException('Data signature verification failed; do not trust this business data content');
}
echo "Data signature verification passed\n";