Skip to content

Python 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 module (aes256gcm_util): 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 module 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 utility module, 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 ​

  • Python 3.6+
  • Dependency: pip install cryptography (shared by AES and RSA)

General AES-256-GCM Utility ​

python
# aes256gcm_util.py
import base64
import os

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes

IV_LENGTH = 12
TAG_LENGTH = 16


def encrypt(plaintext: str, key_base64: str) -> str:
    key = base64.b64decode(key_base64)
    iv = _generate_iv()

    cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend())
    encryptor = cipher.encryptor()
    ciphertext = encryptor.update(plaintext.encode("utf-8")) + encryptor.finalize()
    # Consistent with Java/JCE: iv || ciphertext || tag
    return base64.b64encode(iv + ciphertext + encryptor.tag).decode("utf-8")


def decrypt(encrypted_base64: str, key_base64: str) -> bytes:
    key = base64.b64decode(key_base64)
    data = base64.b64decode(encrypted_base64)

    iv = data[:IV_LENGTH]
    tag = data[-TAG_LENGTH:]
    ciphertext = data[IV_LENGTH:-TAG_LENGTH]

    cipher = Cipher(algorithms.AES(key), modes.GCM(iv, tag=tag), backend=default_backend())
    decryptor = cipher.decryptor()
    return decryptor.update(ciphertext) + decryptor.finalize()


def _generate_iv() -> bytes:
    return os.urandom(IV_LENGTH)

1. userSignature Generation ​

Build the authentication Payload based on aes256gcm_util and encrypt it:

python
# user_signature.py
import json
import time

from aes256gcm_util import encrypt

SIGNATURE_VERSION = "1"


def generate_user_signature(user_id: str, expires_at: int, base64_key: str) -> str:
    if not user_id:
        raise ValueError("user_id must not be empty")
    if not isinstance(expires_at, int) or expires_at <= int(time.time()):
        raise ValueError("expires_at must be an integer Unix timestamp (seconds) greater than the current time")

    payload = json.dumps(
        {"version": SIGNATURE_VERSION, "user_id": user_id, "expires_at": expires_at},
        separators=(",", ":"),
        ensure_ascii=False,
    )
    return encrypt(payload, base64_key)


if __name__ == "__main__":
    base64_key = "Your Base64-encoded 32-byte AES key"
    user_id = "user_123456"
    expires_at = int(time.time()) + 24 * 3600
    print("userSignature:", generate_user_signature(user_id, expires_at, base64_key))

2. sessionKey Decryption ​

Decrypt based on aes256gcm_util and validate the payload fields:

python
# session_key.py
import json
from typing import Optional, Tuple

from aes256gcm_util import decrypt


def decrypt_session_key(
    encrypted_session_key: str,
    base64_key: str,
    expected_user_id: Optional[str] = None,
) -> Tuple[str, str]:
    plaintext_bytes = decrypt(encrypted_session_key, base64_key)
    payload = plaintext_bytes.decode("utf-8")

    try:
        parsed = json.loads(payload)
    except json.JSONDecodeError as e:
        raise ValueError(f"The decrypted payload is not valid JSON: {e}")

    user_id = parsed.get("user_id")
    session_key = parsed.get("session_key")
    if not user_id or not session_key:
        raise ValueError("payload missing required fields user_id / session_key")
    if expected_user_id and user_id != expected_user_id:
        raise ValueError(f"user_id mismatch: expected {expected_user_id}, actual {user_id}")

    return user_id, session_key


if __name__ == "__main__":
    encrypted_session_key = "Base64-encoded encrypted_session_key"
    base64_key = "Your Base64-encoded 32-byte AES key"
    expected_user_id = "user_123456"
    user_id, session_key = decrypt_session_key(encrypted_session_key, base64_key, expected_user_id)
    print(f"user_id: {user_id}, session_key: {session_key}")

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 (the cryptography library defaults to trailer=1), and the signature value is Base64-encoded.

3.1 General RSA Signing/Verification Utility ​

python
# rsa_util.py
import base64

from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa

SALT_LENGTH = 32


def _pss_padding() -> padding.PSS:
    return padding.PSS(mgf=padding.MGF1(hashes.SHA256()), salt_length=SALT_LENGTH)


def sign(content: str, private_key_pem: str) -> str:
    private_key = serialization.load_pem_private_key(
        private_key_pem.encode("utf-8"), password=None, backend=default_backend()
    )
    if not isinstance(private_key, rsa.RSAPrivateKey):
        raise TypeError("private key is not of RSA type")
    signature = private_key.sign(content.encode("utf-8"), _pss_padding(), hashes.SHA256())
    return base64.b64encode(signature).decode("utf-8")


def verify(content: str, sign_value_base64: str, public_key_pem: str) -> bool:
    public_key = serialization.load_pem_public_key(
        public_key_pem.encode("utf-8"), backend=default_backend()
    )
    if not isinstance(public_key, rsa.RSAPublicKey):
        raise TypeError("public key is not of RSA type")
    try:
        public_key.verify(
            base64.b64decode(sign_value_base64),
            content.encode("utf-8"),
            _pss_padding(),
            hashes.SHA256(),
        )
        return True
    except InvalidSignature:
        return False

3.2 Invocation Example ​

python
# verify_data.py
from rsa_util import verify

# public_key_pem: 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)
public_key_pem = "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
content = "content to be verified"
signature = "the Base64 signature value carried in the business data"

if not verify(content, signature, public_key_pem):
    raise ValueError("Data signature verification failed; do not trust this business data content")
print("Data signature verification passed")