Skip to content

Python 示例代码 ​

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

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

通用说明 ​

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

环境依赖 ​

  • Python 3.6+
  • 依赖:pip install cryptography(AES、RSA 共用)

通用 AES-256-GCM 工具 ​

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()
    # 与 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 生成 ​

基于 aes256gcm_util 构造鉴权 Payload 并加密:

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 不能为空")
    if not isinstance(expires_at, int) or expires_at <= int(time.time()):
        raise ValueError("expires_at 必须为大于当前时间的整型 Unix 时间戳(秒)")

    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 = "你的Base64编码的32字节AES密钥"
    user_id = "user_123456"
    expires_at = int(time.time()) + 24 * 3600
    print("userSignature:", generate_user_signature(user_id, expires_at, base64_key))

2. sessionKey 解密 ​

基于 aes256gcm_util 解密并校验载荷字段:

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"解密后的载荷不是合法 JSON: {e}")

    user_id = parsed.get("user_id")
    session_key = parsed.get("session_key")
    if not user_id or not session_key:
        raise ValueError("载荷缺少必要字段 user_id / session_key")
    if expected_user_id and user_id != expected_user_id:
        raise ValueError(f"user_id 不一致: 期望 {expected_user_id}, 实际 {user_id}")

    return user_id, session_key


if __name__ == "__main__":
    encrypted_session_key = "Base64编码的encrypted_session_key"
    base64_key = "你的Base64编码的32字节AES密钥"
    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. 业务数据签名验签 ​

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

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

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("私钥不是 RSA 类型")
    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("公钥不是 RSA 类型")
    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 调用示例 ​

python
# verify_data.py
from rsa_util import verify

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

if not verify(content, signature, public_key_pem):
    raise ValueError("数据验签失败,请勿信任该业务数据内容")
print("数据验签通过")