Guide to Generating User Signatures
The application server is primarily responsible for generating the user authentication signature (userSignature) and returning it to the client. This user authentication signature is the core credential the client uses for identity authentication.
1.1 Prerequisites
Before starting the integration, please ensure the following preparations are complete:
Configure the content encryption key: You need to configure the symmetric key in the SUD OpenPaaS console. Two encryption algorithms are supported:
- AES-256-GCM: The key is 32 bytes (256 bits), Base64-encoded.
- SM4-GCM: The key is 16 bytes (128 bits), Base64-encoded.
Please configure the corresponding type of key based on the chosen algorithm and keep it safe.
1.2 Generating the Authentication Signature
The server needs to construct specific JSON data and encrypt it to generate the user authentication signature (userSignature) required for authentication.
1. Constructing the Encryption Payload
Construct a compact JSON string (no spaces, no line breaks) containing the following fields:
{"version":"1","user_id":"xxx","expires_at":1761638855}| Parameter | Required | Type | Description |
|---|---|---|---|
| version | Yes | string | Protocol version number, currently a fixed value of 1 (no extra spaces) |
| user_id | Yes | string | The user's unique identifier ID (non-empty; recommended to keep consistent with the business-side user ID) |
| expires_at | Yes | int | The Unix timestamp when the signature expires (in seconds, UTC timezone); a validity period of no more than 24 hours is recommended |
Parameter Validation Rules:
versionmust be the string "1" and cannot be modified;user_idcannot be an empty string or a null value;expires_atmust be a positive integer and must be greater than the current timestamp (to avoid the signature expiring as soon as it is generated).
2. Encryption Processing
Using the symmetric key configured in the prerequisites, encrypt the above JSON string according to the following specifications based on the chosen algorithm. The encryption result format is uniformly: Initialization Vector (IV) + Ciphertext + Authentication Tag. Base64-encode this binary data and finally return the Base64-encoded string.
AES-256-GCM Algorithm Parameters:
- Encryption algorithm: AES-256-GCM
- Key length: 256 bits (32 bytes)
- Initialization Vector (IV): must be randomly generated for each encryption, with a length of 12 bytes (96 bits)
- Authentication tag length: 16 bytes (128 bits)
- Character encoding: UTF-8
SM4-GCM Algorithm Parameters:
- Encryption algorithm: SM4-GCM (Chinese national cryptographic algorithm)
- Key length: 128 bits (16 bytes)
- Initialization Vector (IV): must be randomly generated for each encryption, with a length of 12 bytes (96 bits)
- Authentication tag length: 16 bytes (128 bits)
- Character encoding: UTF-8
1.3 Sample Code
General Notes
- The sample code is all developed based on a "Base64-encoded symmetric key";
- The samples contain only the core encryption logic; production environments require additional engineering handling such as logging and exception fallbacks;
- For the SM4-GCM algorithm, some programming languages may require additional third-party libraries (e.g., Java needs BouncyCastle, Go needs tjfoc/gmsm, Python needs gmssl, Node.js needs sm-crypto, etc.); the dependencies are noted in the samples.
Java
Environment dependencies
JDK 8+ (no additional dependencies required; based on the JDK's built-in crypto library)
- AES-256-GCM Example (utility class + calling example)
javaimport javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.util.Base64; public class AESGCMEncryptUtil { private static final String AES_ALGORITHM = "AES"; private static final String AES_TRANSFORMATION = "AES/GCM/NoPadding"; private static final int IV_SIZE_BYTES = 12; private static final int TAG_SIZE_BITS = 128; public static String encrypt(String data, String base64Key) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(base64Key); if (keyBytes.length != 32) { throw new IllegalArgumentException("AES-256 key length must be 32 bytes"); } SecretKeySpec secretKey = new SecretKeySpec(keyBytes, AES_ALGORITHM); byte[] iv = new byte[IV_SIZE_BYTES]; new SecureRandom().nextBytes(iv); Cipher cipher = Cipher.getInstance(AES_TRANSFORMATION); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(TAG_SIZE_BITS, iv)); byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); byte[] ciphertextWithTag = cipher.doFinal(dataBytes); byte[] result = new byte[iv.length + ciphertextWithTag.length]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(ciphertextWithTag, 0, result, iv.length, ciphertextWithTag.length); return Base64.getEncoder().encodeToString(result); } public static void main(String[] args) throws Exception { String payload = "{\"version\":\"1\",\"user_id\":\"user_123456\",\"expires_at\":1761638855}"; String base64Key = "Your Base64-encoded 32-byte AES key"; String userSignature = encrypt(payload, base64Key); System.out.println("AES-256-GCM signature: " + userSignature); } }- SM4-GCM Example (requires the BouncyCastle library)
javaimport org.bouncycastle.jce.provider.BouncyCastleProvider; import javax.crypto.Cipher; import javax.crypto.spec.GCMParameterSpec; import javax.crypto.spec.SecretKeySpec; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; import java.security.Security; import java.util.Base64; public class SM4GCMEncryptUtil { static { Security.addProvider(new BouncyCastleProvider()); } private static final String SM4_ALGORITHM = "SM4"; private static final String SM4_TRANSFORMATION = "SM4/GCM/NoPadding"; private static final int IV_SIZE_BYTES = 12; private static final int TAG_SIZE_BITS = 128; public static String encrypt(String data, String base64Key) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(base64Key); if (keyBytes.length != 16) { throw new IllegalArgumentException("SM4 key length must be 16 bytes"); } SecretKeySpec secretKey = new SecretKeySpec(keyBytes, SM4_ALGORITHM); byte[] iv = new byte[IV_SIZE_BYTES]; new SecureRandom().nextBytes(iv); Cipher cipher = Cipher.getInstance(SM4_TRANSFORMATION, "BC"); cipher.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(TAG_SIZE_BITS, iv)); byte[] dataBytes = data.getBytes(StandardCharsets.UTF_8); byte[] ciphertextWithTag = cipher.doFinal(dataBytes); byte[] result = new byte[iv.length + ciphertextWithTag.length]; System.arraycopy(iv, 0, result, 0, iv.length); System.arraycopy(ciphertextWithTag, 0, result, iv.length, ciphertextWithTag.length); return Base64.getEncoder().encodeToString(result); } public static void main(String[] args) throws Exception { String payload = "{\"version\":\"1\",\"user_id\":\"user_123456\",\"expires_at\":1761638855}"; String base64Key = "Your Base64-encoded 16-byte SM4 key"; String userSignature = encrypt(payload, base64Key); System.out.println("SM4-GCM signature: " + userSignature); } }
Go
Environment dependencies
Go 1.15+ (no additional dependencies required; based on the standard library)
- AES-256-GCM Example
gopackage main import ( "crypto/aes" "crypto/cipher" "crypto/rand" "encoding/base64" "fmt" "io" ) func EncryptAESGCM(data, base64Key string) (string, error) { key, err := base64.StdEncoding.DecodeString(base64Key) if err != nil { return "", fmt.Errorf("key decoding failed: %w", err) } if len(key) != 32 { return "", fmt.Errorf("AES-256 key length must be 32 bytes") } block, err := aes.NewCipher(key) if err != nil { return "", fmt.Errorf("failed to create AES cipher block: %w", err) } iv := make([]byte, 12) if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", fmt.Errorf("failed to generate IV: %w", err) } gcm, err := cipher.NewGCM(block) if err != nil { return "", fmt.Errorf("failed to create GCM: %w", err) } dataBytes := []byte(data) ciphertextWithTag := gcm.Seal(nil, iv, dataBytes, nil) result := append(iv, ciphertextWithTag...) return base64.StdEncoding.EncodeToString(result), nil } func main() { payload := `{"version":"1","user_id":"user_123456","expires_at":1761638855}` base64Key := "Your Base64-encoded 32-byte AES key" sig, err := EncryptAESGCM(payload, base64Key) if err != nil { fmt.Printf("AES encryption failed: %v\n", err) return } fmt.Println("AES-256-GCM signature:", sig) }- SM4-GCM Example (requires the tjfoc/gmsm library)
- Dependency:
go get -u github.com/tjfoc/gmsm
gopackage main import ( "crypto/rand" "encoding/base64" "fmt" "io" "github.com/tjfoc/gmsm/sm4" ) func EncryptSM4GCM(data, base64Key string) (string, error) { key, err := base64.StdEncoding.DecodeString(base64Key) if err != nil { return "", fmt.Errorf("key decoding failed: %w", err) } if len(key) != 16 { return "", fmt.Errorf("SM4 key length must be 16 bytes") } block, err := sm4.NewCipher(key) if err != nil { return "", fmt.Errorf("failed to create SM4 cipher block: %w", err) } iv := make([]byte, 12) if _, err := io.ReadFull(rand.Reader, iv); err != nil { return "", fmt.Errorf("failed to generate IV: %w", err) } gcm, err := cipher.NewGCM(block) // Note: the block returned by gmsm's sm4.NewCipher implements the cipher.Block interface and can be used directly with cipher.NewGCM if err != nil { return "", fmt.Errorf("failed to create GCM: %w", err) } dataBytes := []byte(data) ciphertextWithTag := gcm.Seal(nil, iv, dataBytes, nil) result := append(iv, ciphertextWithTag...) return base64.StdEncoding.EncodeToString(result), nil } func main() { payload := `{"version":"1","user_id":"user_123456","expires_at":1761638855}` base64Key := "Your Base64-encoded 16-byte SM4 key" sig, err := EncryptSM4GCM(payload, base64Key) if err != nil { fmt.Printf("SM4 encryption failed: %v\n", err) return } fmt.Println("SM4-GCM signature:", sig) }
Python
Environment dependencies
- Python 3.6+
AES-256-GCM Example
Dependency:
pip install cryptographypythonimport base64 import os from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend def encrypt_aes_gcm(data: str, base64_key: str) -> str: key = base64.b64decode(base64_key) if len(key) != 32: raise ValueError("AES-256 key length must be 32 bytes") iv = os.urandom(12) cipher = Cipher(algorithms.AES(key), modes.GCM(iv), backend=default_backend()) encryptor = cipher.encryptor() ciphertext = encryptor.update(data.encode('utf-8')) + encryptor.finalize() tag = encryptor.tag result = iv + ciphertext + tag return base64.b64encode(result).decode('utf-8') if __name__ == "__main__": payload = '{"version":"1","user_id":"user_123456","expires_at":1761638855}' base64_key = "Your Base64-encoded 32-byte AES key" sig = encrypt_aes_gcm(payload, base64_key) print("AES-256-GCM signature:", sig)SM4-GCM Example (requires the gmssl library)
Dependency:
pip install gmsslpythonimport base64 import os from gmssl.sm4 import CryptSM4, SM4_GCM def encrypt_sm4_gcm(data: str, base64_key: str) -> str: key = base64.b64decode(base64_key) if len(key) != 16: raise ValueError("SM4 key length must be 16 bytes") iv = os.urandom(12) cipher = CryptSM4() cipher.set_key(key, SM4_GCM) # gmssl's GCM mode requires handling the IV and tag manually # This library's encrypt_gcm returns (ciphertext, tag) ciphertext, tag = cipher.encrypt_gcm(data.encode('utf-8'), iv) result = iv + ciphertext + tag return base64.b64encode(result).decode('utf-8') if __name__ == "__main__": payload = '{"version":"1","user_id":"user_123456","expires_at":1761638855}' base64_key = "Your Base64-encoded 16-byte SM4 key" sig = encrypt_sm4_gcm(payload, base64_key) print("SM4-GCM signature:", sig)
PHP
Environment dependencies
- PHP 7.2+
- The OpenSSL extension enabled (enable
extension=opensslin php.ini)
AES-256-GCM Example
php<?php function encryptAESGCM(string $data, string $base64Key): string { $key = base64_decode($base64Key, true); if ($key === false || strlen($key) !== 32) { throw new Exception("AES-256 key must be a 32-byte Base64-encoded string"); } $iv = random_bytes(12); $tag = ''; $ciphertext = openssl_encrypt( $data, 'aes-256-gcm', $key, OPENSSL_RAW_DATA, $iv, $tag ); if ($ciphertext === false) { throw new Exception("Encryption failed: " . openssl_error_string()); } $result = $iv . $ciphertext . $tag; return base64_encode($result); } // Calling example $payload = '{"version":"1","user_id":"user_123456","expires_at":1761638855}'; $base64Key = 'Your Base64-encoded 32-byte AES key'; $signature = encryptAESGCM($payload, $base64Key); echo "AES-256-GCM signature: " . $signature; ?>SM4-GCM Example (requires a third-party extension, such as php-sm4 or OpenSSL's SM4 support)
Note: PHP's OpenSSL extension currently does not support SM4-GCM. It is recommended to use a third-party PHP extension (such as php-sm4) or to call an encryption service via HTTP. The following example assumes there is a class Sm4GcmEncryptor that supports SM4-GCM (which you need to implement yourself or use a third-party library).
php<?php // Assume a library that supports SM4-GCM has already been imported // For example, using the php-sm4 extension (https://github.com/lizhichao/sm4) // This extension provides the \Sm4\Sm4 class, but you need to implement the GCM mode yourself // This is only pseudo-code for illustration function encryptSM4GCM(string $data, string $base64Key): string { $key = base64_decode($base64Key, true); if ($key === false || strlen($key) !== 16) { throw new Exception("SM4 key must be a 16-byte Base64-encoded string"); } $iv = random_bytes(12); // Call the third-party library's GCM encryption method, returning the ciphertext and tag // Assume $ciphertextWithTag is already ciphertext + tag // This is shown as pseudo-code; adjust according to the library you use $cipher = new \Sm4\Sm4(); // Assumed to exist $ciphertextWithTag = $cipher->encryptGcm($data, $key, $iv); // Returns ciphertext + tag $result = $iv . $ciphertextWithTag; return base64_encode($result); } // Calling example $payload = '{"version":"1","user_id":"user_123456","expires_at":1761638855}'; $base64Key = 'Your Base64-encoded 16-byte SM4 key'; $signature = encryptSM4GCM($payload, $base64Key); echo "SM4-GCM signature: " . $signature; ?>
Node.js
Environment dependencies
- Node.js 12+ (no additional dependencies required; based on the built-in crypto module)
AES-256-GCM Example
javascriptconst crypto = require('crypto'); function encryptAESGCM(data, base64Key) { const key = Buffer.from(base64Key, 'base64'); if (key.length !== 32) throw new Error('AES-256 key length must be 32 bytes'); const iv = crypto.randomBytes(12); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); const ciphertext = Buffer.concat([cipher.update(data, 'utf8'), cipher.final()]); const tag = cipher.getAuthTag(); const result = Buffer.concat([iv, ciphertext, tag]); return result.toString('base64'); } // Calling example const payload = '{"version":"1","user_id":"user_123456","expires_at":1761638855}'; const base64Key = 'Your Base64-encoded 32-byte AES key'; const signature = encryptAESGCM(payload, base64Key); console.log('AES-256-GCM signature:', signature);SM4-GCM Example (requires the sm-crypto library)
Dependency:
npm install sm-crypto
const sm4 = require('sm-crypto').sm4;
function encryptSM4GCM(data, base64Key) {
const key = Buffer.from(base64Key, 'base64');
if (key.length !== 16) throw new Error('SM4 key length must be 16 bytes');
const iv = crypto.randomBytes(12); // Note: sm-crypto's sm4.gcm requires a Buffer or Uint8Array
// sm-crypto's GCM encryption method returns { ciphertext, tag }
// Note: this library's sm4.gcm.encrypt requires key, iv, plaintext, aad? — consult the docs for details
// Here we assume the usage is as follows:
const encrypted = sm4.gcm.encrypt(data, key, iv, null); // Returns { ciphertext, tag }
const ciphertext = Buffer.from(encrypted.ciphertext, 'hex');
const tag = Buffer.from(encrypted.tag, 'hex');
const result = Buffer.concat([iv, ciphertext, tag]);
return result.toString('base64');
}
// Calling example
const payload = '{"version":"1","user_id":"user_123456","expires_at":1761638855}';
const base64Key = 'Your Base64-encoded 16-byte SM4 key';
const signature = encryptSM4GCM(payload, base64Key);
console.log('SM4-GCM signature:', signature);1.4 Troubleshooting Common Issues
Common Causes of Encryption Failure
- Incorrect key format: the key is not valid Base64 encoding, or its decoded length does not match the chosen algorithm (AES-256 requires 32 bytes, SM4 requires 16 bytes).
- Incorrect payload format: using formatted JSON (with spaces/line breaks) or incorrect field types (e.g., expires_at as a string);
- Inconsistent character encoding: the string was not encrypted using UTF-8 encoding;
- Insecure IV generation: using a fixed IV or a weak random number generator (you must use a cryptographically secure random number).
- Inconsistent cross-language concatenation order: the encryption result must strictly follow the order of IV (12 bytes) + ciphertext + authentication tag (16 bytes).
- Abnormal expires_at: the timestamp is non-integer, already expired, or has the wrong timezone (not UTC).
Additional Checks for Signature Authentication Failure
- Confirm that
versionis fixed as the string "1", not the number 1; - Confirm that the
expires_attimestamp has not expired and is in the UTC timezone; - Confirm that the JSON string before encryption has not undergone any format modifications (such as extra commas or field order changes);
- If using SM4-GCM, ensure that the encryption library used is compatible with the decryption side (e.g., consistent tag length and IV length).
