Java 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 class (AES256GCMUtil): a general-purpose symmetric encryption/decryption implementation, fully 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 class to perform Payload construction and field validation, covering userSignature generation and sessionKey decryption respectively.
- The AES byte layout is uniformly:
iv(12) || ciphertext+tag, then Base64-encoded as a whole (wheretagis automatically appended to the end of the ciphertext by GCM, with a length of 16 bytes). - The RSA part (§3 Business data signature verification) provides an independent
RSAUtilutility class, 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
JDK 8+.
The AES part is based on the JDK built-in encryption library and requires no additional dependencies.
The RSA part (§3) relies on BouncyCastle to parse PEM-formatted public/private keys:
xml<dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk15on</artifactId> <version>1.70</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcpkix-jdk15on</artifactId> <version>1.70</version> </dependency>To avoid introducing a third-party JSON library, the AES business wrapper example uses
String.formatfor assembly and regular expressions for parsing; in production it is recommended to replace this with a mature JSON library such as Jackson or Gson.
General AES-256-GCM Utility
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.util.Base64;
public class AES256GCMUtil {
private static final String ALGORITHM = "AES";
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
private static final int IV_LENGTH = 12;
private static final int TAG_SIZE = 128;
public static String encrypt(String plaintext, String keyBase64) throws Exception {
byte[] key = Base64.getDecoder().decode(keyBase64);
byte[] iv = generateIV();
byte[] plainBytes = plaintext.getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
GCMParameterSpec gcmSpec = new GCMParameterSpec(TAG_SIZE, iv);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmSpec);
byte[] cipherBytes = cipher.doFinal(plainBytes);
byte[] result = new byte[IV_LENGTH + cipherBytes.length];
System.arraycopy(iv, 0, result, 0, iv.length);
System.arraycopy(cipherBytes, 0, result, iv.length, cipherBytes.length);
return Base64.getEncoder().encodeToString(result);
}
public static byte[] decrypt(String encryptedBase64, String keyBase64) throws Exception {
byte[] key = Base64.getDecoder().decode(keyBase64);
byte[] encryptedBytes = Base64.getDecoder().decode(encryptedBase64);
byte[] iv = new byte[IV_LENGTH];
System.arraycopy(encryptedBytes, 0, iv, 0, IV_LENGTH);
byte[] cipherBytes = new byte[encryptedBytes.length - IV_LENGTH];
System.arraycopy(encryptedBytes, IV_LENGTH, cipherBytes, 0, cipherBytes.length);
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
SecretKeySpec keySpec = new SecretKeySpec(key, ALGORITHM);
GCMParameterSpec gcmSpec = new GCMParameterSpec(TAG_SIZE, iv);
cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmSpec);
return cipher.doFinal(cipherBytes);
}
private static byte[] generateIV() {
byte[] iv = new byte[IV_LENGTH];
new SecureRandom().nextBytes(iv);
return iv;
}
}1. userSignature Generation
Build the authentication Payload based on AES256GCMUtil and encrypt it:
import java.time.Instant;
public class UserSignatureGenerator {
private static final String SIGNATURE_VERSION = "1";
public static String generate(String userId, long expiresAt, String base64Key) throws Exception {
if (userId == null || userId.isEmpty()) {
throw new IllegalArgumentException("user_id must not be empty");
}
if (expiresAt <= Instant.now().getEpochSecond()) {
throw new IllegalArgumentException("expires_at must be a Unix timestamp (seconds) greater than the current time");
}
String payload = String.format(
"{\"version\":\"%s\",\"user_id\":\"%s\",\"expires_at\":%d}",
SIGNATURE_VERSION, escapeJsonString(userId), expiresAt
);
return AES256GCMUtil.encrypt(payload, base64Key);
}
private static String escapeJsonString(String s) {
return s.replace("\\", "\\\\").replace("\"", "\\\"");
}
public static void main(String[] args) throws Exception {
String base64Key = "Your Base64-encoded 32-byte AES key";
String userId = "user_123456";
long expiresAt = Instant.now().getEpochSecond() + 24 * 3600;
String userSignature = generate(userId, expiresAt, base64Key);
System.out.println("userSignature: " + userSignature);
}
}2. sessionKey Decryption
Decrypt based on AES256GCMUtil and validate the payload fields:
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SessionKeyDecryptor {
public static class SessionPayload {
public final String userId;
public final String sessionKey;
public SessionPayload(String userId, String sessionKey) {
this.userId = userId;
this.sessionKey = sessionKey;
}
}
public static SessionPayload decrypt(String encryptedSessionKey, String base64Key, String expectedUserId) throws Exception {
byte[] plaintextBytes = AES256GCMUtil.decrypt(encryptedSessionKey, base64Key);
String payload = new String(plaintextBytes, StandardCharsets.UTF_8);
String userId = extractStringField(payload, "user_id");
String sessionKey = extractStringField(payload, "session_key");
if (userId == null || sessionKey == null) {
throw new IllegalStateException("payload missing required fields user_id / session_key");
}
if (expectedUserId != null && !expectedUserId.equals(userId)) {
throw new IllegalStateException("user_id mismatch: expected " + expectedUserId + ", actual " + userId);
}
return new SessionPayload(userId, sessionKey);
}
private static String extractStringField(String json, String field) {
Pattern p = Pattern.compile("\"" + Pattern.quote(field) + "\"\\s*:\\s*\"((?:\\\\.|[^\"\\\\])*)\"");
Matcher m = p.matcher(json);
if (!m.find()) return null;
return m.group(1).replace("\\\"", "\"").replace("\\\\", "\\");
}
public static void main(String[] args) throws Exception {
String encryptedSessionKey = "Base64-encoded encrypted_session_key";
String base64Key = "Your Base64-encoded 32-byte AES key";
String expectedUserId = "user_123456";
SessionPayload payload = decrypt(encryptedSessionKey, base64Key, expectedUserId);
System.out.println("user_id: " + payload.userId + ", session_key: " + payload.sessionKey);
}
}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, and the signature value is Base64-encoded.
3.1 General RSA Signing/Verification Utility
import org.bouncycastle.asn1.pkcs.PrivateKeyInfo;
import org.bouncycastle.asn1.x509.SubjectPublicKeyInfo;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMKeyPair;
import org.bouncycastle.openssl.PEMParser;
import org.bouncycastle.openssl.jcajce.JcaPEMKeyConverter;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.Signature;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.PSSParameterSpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;
public class RSAUtil {
private static final String ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "RSASSA-PSS";
private static final PSSParameterSpec PSS_SPEC =
new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1);
static {
if (Security.getProvider(BouncyCastleProvider.PROVIDER_NAME) == null) {
Security.addProvider(new BouncyCastleProvider());
}
}
/** Uses the application private key to sign the content and returns a Base64 string. */
public static String sign(String content, String privateKeyPem) throws Exception {
PrivateKey privateKey = readPrivateKey(privateKeyPem);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.setParameter(PSS_SPEC);
signature.initSign(privateKey);
signature.update(content.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(signature.sign());
}
/** Uses the public key delivered by SUD OpenPaaS to verify the signature. */
public static boolean verify(String content, String signValueBase64, String publicKeyPem) throws Exception {
PublicKey publicKey = readPublicKey(publicKeyPem);
Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
signature.setParameter(PSS_SPEC);
signature.initVerify(publicKey);
signature.update(content.getBytes(StandardCharsets.UTF_8));
return signature.verify(Base64.getDecoder().decode(signValueBase64));
}
private static PrivateKey readPrivateKey(String key) throws Exception {
try (PEMParser pemParser = new PEMParser(new StringReader(key))) {
Object object = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter()
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
if (object instanceof PEMKeyPair) {
return converter.getKeyPair((PEMKeyPair) object).getPrivate();
}
if (object instanceof PrivateKeyInfo) {
return converter.getPrivateKey((PrivateKeyInfo) object);
}
} catch (Exception ignore) {
// Fall back to raw Base64 PKCS#8
}
byte[] decoded = Base64.getDecoder().decode(key.replaceAll("\\s", ""));
return KeyFactory.getInstance(ALGORITHM).generatePrivate(new PKCS8EncodedKeySpec(decoded));
}
private static PublicKey readPublicKey(String key) throws Exception {
try (PEMParser pemParser = new PEMParser(new StringReader(key))) {
Object object = pemParser.readObject();
JcaPEMKeyConverter converter = new JcaPEMKeyConverter()
.setProvider(BouncyCastleProvider.PROVIDER_NAME);
if (object instanceof SubjectPublicKeyInfo) {
return converter.getPublicKey((SubjectPublicKeyInfo) object);
}
} catch (Exception ignore) {
// Fall back to raw Base64 X.509
}
byte[] decoded = Base64.getDecoder().decode(key.replaceAll("\\s", ""));
return KeyFactory.getInstance(ALGORITHM).generatePublic(new X509EncodedKeySpec(decoded));
}
}3.2 Invocation Example
// publicKeyPem: 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)
boolean ok = RSAUtil.verify(content, signature, publicKeyPem);
if (!ok) {
throw new IllegalArgumentException("Data signature verification failed; do not trust this business data content");
}