Python Example Code
1. Core Security Component (sud_security_util.py)
python
import base64
import json
import os
import time
from typing import Any, Dict, Tuple
from cryptography.exceptions import InvalidSignature
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.x509 import load_pem_x509_certificate
class SudSecurityUtil:
"""SUD OpenPaaS API secure communication core utility class"""
@staticmethod
def encrypt_request(url_path: str, app_id: str, key_sn: str, sym_key_base64: str, req_data: Dict[str, Any]) -> Tuple[int, Dict[str, str]]:
"""
1. Request business data encryption (AES-256-GCM)
"""
timestamp = int(time.time())
# Generate a 16-byte random number and use URL-safe Base64 encoding (stripping the trailing '=')
nonce = base64.urlsafe_b64encode(os.urandom(16)).decode('utf-8').rstrip('=')
# Fill in the security check fields
req_data['_n'] = nonce
req_data['_appid'] = app_id
req_data['_timestamp'] = timestamp
# Python's json.dumps includes spaces by default; you must use separators=(',', ':') to compress it into a compact format
plaintext = json.dumps(req_data, separators=(',', ':'), ensure_ascii=False)
# Concatenate AAD: urlpath|appid|timestamp|sn
aad = f"{url_path}|{app_id}|{timestamp}|{key_sn}"
real_key = base64.b64decode(sym_key_base64)
iv = os.urandom(12) # GCM recommends a 12-byte IV
aesgcm = AESGCM(real_key)
# The encrypt method internally appends the 16-byte AuthTag to the end of the ciphertext slice
ciphertext_with_tag = aesgcm.encrypt(
nonce=iv,
data=plaintext.encode('utf-8'),
associated_data=aad.encode('utf-8')
)
# Separate the real ciphertext from the AuthTag
ciphertext = ciphertext_with_tag[:-16]
auth_tag = ciphertext_with_tag[-16:]
http_body = {
"iv": base64.b64encode(iv).decode('utf-8'),
"data": base64.b64encode(ciphertext).decode('utf-8'),
"authtag": base64.b64encode(auth_tag).decode('utf-8')
}
return timestamp, http_body
@staticmethod
def sign_request(url_path: str, app_id: str, timestamp: int, req_data_json: str, private_key_pem: str) -> str:
"""
2. Request message signing (RSA-PSS)
"""
# Option B: concatenate strictly in order; a trailing \n must never be added
payload = f"{url_path}\n{app_id}\n{timestamp}\n{req_data_json}"
# Load the PKCS#8 format private key
private_key = load_pem_private_key(private_key_pem.encode('utf-8'), password=None)
# Perform PSS signing
signature = private_key.sign(
payload.encode('utf-8'),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=32 # The salt length must strictly align with SHA256 (32 bytes)
),
hashes.SHA256()
)
return base64.b64encode(signature).decode('utf-8')
@staticmethod
def verify_response_signature(url_path: str, expected_app_id: str, local_cert_sn: str, platform_cert_pem: str,
resp_app_id: str, resp_ts: int, resp_sn: str, resp_sig: str,
resp_deprecated_sn: str, resp_deprecated_sig: str, resp_data_json: str) -> bool:
"""
3. Response message signature verification (RSA-PSS)
"""
if expected_app_id != resp_app_id:
raise ValueError("Security check failed: the response AppId does not match the local one")
# Certificate serial number matching and smooth rotation support
signature_base64 = ""
if local_cert_sn == resp_sn:
signature_base64 = resp_sig
elif resp_deprecated_sn and local_cert_sn == resp_deprecated_sn:
signature_base64 = resp_deprecated_sig if resp_deprecated_sig else resp_sig
else:
raise ValueError(f"Signature verification failed: the local certificate serial number ({local_cert_sn}) does not match the platform's current serial number ({resp_sn})")
payload = f"{url_path}\n{resp_app_id}\n{resp_ts}\n{resp_data_json}"
# Load the X.509 platform public key certificate
cert = load_pem_x509_certificate(platform_cert_pem.encode('utf-8'))
public_key = cert.public_key()
try:
public_key.verify(
base64.b64decode(signature_base64),
payload.encode('utf-8'),
padding.PSS(
mgf=padding.MGF1(hashes.SHA256()),
salt_length=32
),
hashes.SHA256()
)
return True
except InvalidSignature:
return False
@staticmethod
def decrypt_response(url_path: str, app_id: str, resp_ts: int, key_sn: str, sym_key_base64: str, resp_data_json: str) -> Dict[str, Any]:
"""
4. Response ciphertext decryption (AES-256-GCM)
"""
enc_body = json.loads(resp_data_json)
iv = base64.b64decode(enc_body['iv'])
data = base64.b64decode(enc_body['data'])
auth_tag = base64.b64decode(enc_body['authtag'])
aad = f"{url_path}|{app_id}|{resp_ts}|{key_sn}"
real_key = base64.b64decode(sym_key_base64)
# The Cryptography library requires the ciphertext and the AuthTag to be concatenated together when passed in
combined_data = data + auth_tag
aesgcm = AESGCM(real_key)
try:
# The decrypt method internally verifies the validity of the AuthTag automatically
plaintext_bytes = aesgcm.decrypt(
nonce=iv,
data=combined_data,
associated_data=aad.encode('utf-8')
)
except Exception as e:
raise ValueError(f"Decryption failed: AuthTag verification did not pass or the ciphertext has been tampered with - {str(e)}")
real_resp = json.loads(plaintext_bytes.decode('utf-8'))
# Strong validation of the internal security fields
if real_resp.get('_appid') != app_id or real_resp.get('_timestamp') != resp_ts:
raise ValueError("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
# current_ts = int(time.time())
# if abs(current_ts - real_resp.get('_timestamp', 0)) > 300:
# raise ValueError("Security check failed: the response data deviates from the current time by more than 5 minutes")
return real_resp2. Business Invocation Demo (demo.py)
python
import json
from sud_security_util import SudSecurityUtil
# Simulated global application configuration
CONFIG = {
"app_id": "cp_10010",
"url_path": "https://api.sud.com/v1/game/login", # Option B: full path
"sym_key_sn": "key_v1",
"sym_key": "otUpngOjU+nVQaWJIC3D/yMLV17RKaP6t4Ot9tbnzLY=",
"private_key_pem": "-----BEGIN PRIVATE KEY-----\nMIIEvQI... (application private key) ...W6w=\n-----END PRIVATE KEY-----",
"platform_cert_sn": "sud_cert_v1",
"platform_cert_pem": "-----BEGIN CERTIFICATE-----\nMIID0jC... (SUD platform public key certificate) ...Q==\n-----END CERTIFICATE-----"
}
def main():
try:
print("=== 1. Send request: encrypt and sign business data ===")
# Raw business request parameters
biz_req = {
"appid": CONFIG["app_id"],
"sud_uid": "user_889900",
"scene": 0,
"client_ip": "127.0.0.1"
}
# Step A: encryption
req_ts, http_body_dict = SudSecurityUtil.encrypt_request(
CONFIG["url_path"], CONFIG["app_id"], CONFIG["sym_key_sn"], CONFIG["sym_key"], biz_req
)
# Emphasizing again: use separators to ensure the JSON has no extra spaces
req_data_json = json.dumps(http_body_dict, separators=(',', ':'))
# Step B: signing
req_sig = SudSecurityUtil.sign_request(
CONFIG["url_path"], CONFIG["app_id"], req_ts, req_data_json, CONFIG["private_key_pem"]
)
print(f"HTTP Header X-Sud-Timestamp: {req_ts}")
print(f"HTTP Header X-Sud-Signature: {req_sig}")
print(f"HTTP Body: {req_data_json}")
print("\n=== 2. Receive response: verify signature and decrypt ciphertext ===")
# Simulate the data obtained from the HTTP response
resp_ts = req_ts
resp_header_app_id = CONFIG["app_id"]
resp_header_sn = CONFIG["platform_cert_sn"]
resp_header_sig = req_sig # For demonstration; in practice this is the received signature
resp_body_json = '{"iv":"r2WDQt56rEAmMuoR","data":"HExs...","authtag":"z2BF..."}'
# Step C: signature verification
is_sig_valid = SudSecurityUtil.verify_response_signature(
CONFIG["url_path"], CONFIG["app_id"], CONFIG["platform_cert_sn"], CONFIG["platform_cert_pem"],
resp_header_app_id, resp_ts, resp_header_sn, resp_header_sig,
"", "", resp_body_json
)
if is_sig_valid:
print("Response signature verification succeeded!")
# Step D: decryption
decrypted_biz_data = SudSecurityUtil.decrypt_response(
CONFIG["url_path"], CONFIG["app_id"], resp_ts, CONFIG["sym_key_sn"], CONFIG["sym_key"], resp_body_json
)
print("Response decryption succeeded, business data:")
print(json.dumps(decrypted_biz_data, indent=4, ensure_ascii=False))
except ValueError as e:
print(f"Flow interrupted: {str(e)}")
except Exception as e:
print(f"An unknown error occurred: {str(e)}")
if __name__ == "__main__":
main()