Skip to content

PHP Example Code ​

1. Core Security Component (SudSecurityUtil.php) ​

php
<?php

namespace Sud\Security;

use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;
use Exception;
use RuntimeException;

class SudSecurityUtil
{
    /**
     * 1. Request business data encryption (AES-256-GCM)
     *
     * @param string $urlPath      full path including the domain
     * @param string $appId        application unique identifier AppId
     * @param string $keySn        symmetric key serial number
     * @param string $symKeyBase64 symmetric key Base64 string
     * @param array  $reqData      raw business request data array
     * @return array associative array containing the request timestamp (req_ts) and the JSON ciphertext (req_data)
     */
    public static function encryptRequest(string $urlPath, string $appId, string $keySn, string $symKeyBase64, array $reqData): array
    {
        $timestamp = time();
        // Generate a 16-byte random number and convert it to URL-safe Base64 (without padding '=')
        $nonceBytes = random_bytes(16);
        $nonce = rtrim(strtr(base64_encode($nonceBytes), '+/', '-_'), '=');

        // Fill in the security check fields
        $reqData['_n'] = $nonce;
        $reqData['_appid'] = $appId;
        $reqData['_timestamp'] = $timestamp;

        // Use JSON_UNESCAPED_UNICODE and JSON_UNESCAPED_SLASHES to keep the format compact and not escape non-ASCII characters/slashes
        $plaintext = json_encode($reqData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);

        // Concatenate AAD: urlpath|appid|timestamp|sn
        $aad = "{$urlPath}|{$appId}|{$timestamp}|{$keySn}";
        
        $realKey = base64_decode($symKeyBase64);
        $iv = random_bytes(12); // GCM recommends a 12-byte IV
        $authTag = ''; // Will be assigned by reference by openssl_encrypt

        // Perform AES-256-GCM encryption
        $ciphertext = openssl_encrypt(
            $plaintext,
            'aes-256-gcm',
            $realKey,
            OPENSSL_RAW_DATA,
            $iv,
            $authTag,
            $aad,
            16
        );

        if ($ciphertext === false) {
            throw new RuntimeException("AES-GCM encryption failed");
        }

        $httpBody = [
            'iv' => base64_encode($iv),
            'data' => base64_encode($ciphertext),
            'authtag' => base64_encode($authTag)
        ];

        return [
            'req_ts' => $timestamp,
            'req_data' => json_encode($httpBody, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
        ];
    }

    /**
     * 2. Request message signing (RSA-PSS)
     */
    public static function signRequest(string $urlPath, string $appId, int $timestamp, string $reqDataJson, string $privateKeyPem): string
    {
        // Concatenate strictly in order
        $payload = "{$urlPath}\n{$appId}\n{$timestamp}\n{$reqDataJson}";

        // Load the private key (phpseclib automatically supports both PKCS#1 and PKCS#8 formats)
        $privateKey = PublicKeyLoader::load($privateKeyPem)
            ->withHash('sha256')
            ->withMGFHash('sha256')
            ->withSaltLength(32) // The PSS salt length must align with SHA256 (32 bytes)
            ->withPadding(RSA::SIGNATURE_PSS);

        $signature = $privateKey->sign($payload);
        return base64_encode($signature);
    }

    /**
     * 3. Response message signature verification (RSA-PSS)
     */
    public static function verifyResponseSignature(
        string $urlPath, string $expectedAppId, string $localCertSn, string $platformCertPem,
        string $respAppId, int $respTs, string $respSn, string $respSig,
        ?string $respDeprecatedSn, ?string $respDeprecatedSig, string $respDataJson
    ): bool {
        // Basic security check
        if ($expectedAppId !== $respAppId) {
            throw new Exception("Security check failed: the response AppId does not match the local one");
        }

        // Certificate serial number matching and smooth rotation support
        $signatureBase64 = '';
        if ($localCertSn === $respSn) {
            $signatureBase64 = $respSig;
        } elseif (!empty($respDeprecatedSn) && $localCertSn === $respDeprecatedSn) {
            $signatureBase64 = (!empty($respDeprecatedSig)) ? $respDeprecatedSig : $respSig;
        } else {
            throw new Exception("Signature verification failed: the local certificate serial number ({$localCertSn}) does not match the platform's current serial number ({$respSn})");
        }

        $payload = "{$urlPath}\n{$respAppId}\n{$respTs}\n{$respDataJson}";
        $signatureBytes = base64_decode($signatureBase64);

        // Load the platform public key certificate
        $publicKey = PublicKeyLoader::load($platformCertPem)
            ->withHash('sha256')
            ->withMGFHash('sha256')
            ->withSaltLength(32)
            ->withPadding(RSA::SIGNATURE_PSS);

        return $publicKey->verify($payload, $signatureBytes);
    }

    /**
     * 4. Response ciphertext decryption (AES-256-GCM)
     */
    public static function decryptResponse(string $urlPath, string $appId, int $respTs, string $keySn, string $symKeyBase64, string $respDataJson): array
    {
        $encBody = json_decode($respDataJson, true);
        if (!$encBody || !isset($encBody['iv'], $encBody['data'], $encBody['authtag'])) {
            throw new Exception("Invalid ciphertext JSON format");
        }

        $iv = base64_decode($encBody['iv']);
        $ciphertext = base64_decode($encBody['data']);
        $authTag = base64_decode($encBody['authtag']);

        $aad = "{$urlPath}|{$appId}|{$respTs}|{$keySn}";
        $realKey = base64_decode($symKeyBase64);

        // Perform decryption (returns false if AuthTag verification fails or the ciphertext has been tampered with)
        $plaintext = openssl_decrypt(
            $ciphertext,
            'aes-256-gcm',
            $realKey,
            OPENSSL_RAW_DATA,
            $iv,
            $authTag,
            $aad
        );

        if ($plaintext === false) {
            throw new Exception("Decryption failed: AuthTag verification did not pass or the ciphertext has been tampered with");
        }

        $realResp = json_decode($plaintext, true);

        // Strong validation of the internal security fields
        if (!isset($realResp['_appid'], $realResp['_timestamp']) ||
            $realResp['_appid'] !== $appId ||
            (int)$realResp['_timestamp'] !== $respTs) {
            throw new Exception("Security field validation failed: the _appid or _timestamp inside the response plaintext has been illegally tampered with");
        }

        // You can uncomment this during joint debugging to perform anti-replay validation
        // if (abs(time() - (int)$realResp['_timestamp']) > 300) {
        //     throw new Exception("Security check failed: the response data deviates from the current time by more than 5 minutes");
        // }

        return $realResp;
    }
}

2. Business Invocation Demo (demo.php) ​

php
<?php

require __DIR__ . '/vendor/autoload.php';

use Sud\Security\SudSecurityUtil;

// Simulated global application configuration
$config = [
    'appId' => 'cp_10010',
    'urlPath' => 'https://api.sud.com/v1/game/login',
    'symKeySn' => 'key_v1',
    'symKey' => 'otUpngOjU+nVQaWJIC3D/yMLV17RKaP6t4Ot9tbnzLY=',
    'privateKeyPem' => "-----BEGIN PRIVATE KEY-----\nMIIEvQIB... (application private key) ...W6w=\n-----END PRIVATE KEY-----",
    'platformCertSn' => 'sud_cert_v1',
    'platformCertPem' => "-----BEGIN CERTIFICATE-----\nMIID0j... (SUD platform public key certificate) ...Q==\n-----END CERTIFICATE-----"
];

try {
    echo "=== 1. Send request: encrypt and sign business data ===\n";

    // Raw business request parameters
    $bizReq = [
        'appid' => $config['appId'],
        'sud_uid' => 'user_889900',
        'scene' => 0,
        'client_ip' => '127.0.0.1'
    ];

    // Step A: encryption
    $encResult = SudSecurityUtil::encryptRequest(
        $config['urlPath'], $config['appId'], $config['symKeySn'], $config['symKey'], $bizReq
    );
    
    $reqTs = $encResult['req_ts'];
    $reqDataJson = $encResult['req_data'];

    // Step B: signing
    $reqSig = SudSecurityUtil::signRequest(
        $config['urlPath'], $config['appId'], $reqTs, $reqDataJson, $config['privateKeyPem']
    );

    echo "HTTP Header X-Sud-Timestamp: {$reqTs}\n";
    echo "HTTP Header X-Sud-Signature: {$reqSig}\n";
    echo "HTTP Body: {$reqDataJson}\n";


    echo "\n=== 2. Receive response: verify signature and decrypt ciphertext ===\n";

    // Simulate the data obtained from the HTTP response
    $respTs = $reqTs;
    $respHeaderAppId = $config['appId'];
    $respHeaderSn = $config['platformCertSn'];
    $respHeaderSig = $reqSig; // For demonstration; in practice this is the received signature
    $respBodyJson = '{"iv":"r2WDQt56rEAmMuoR","data":"HExs...","authtag":"z2BF..."}';

    // Step C: signature verification
    $isSigValid = SudSecurityUtil::verifyResponseSignature(
        $config['urlPath'], $config['appId'], $config['platformCertSn'], $config['platformCertPem'],
        $respHeaderAppId, $respTs, $respHeaderSn, $respHeaderSig,
        null, null, $respBodyJson
    );

    if ($isSigValid) {
        echo "Response signature verification succeeded!\n";

        // Step D: decryption
        $decryptedBizData = SudSecurityUtil::decryptResponse(
            $config['urlPath'], $config['appId'], $respTs, $config['symKeySn'], $config['symKey'], $respBodyJson
        );
        
        echo "Response decryption succeeded, business data:\n";
        print_r($decryptedBizData);
    }

} catch (Exception $e) {
    echo "Flow interrupted: " . $e->getMessage() . "\n";
}