Java Example Code
1. Core Security Component (SudApiSecurityUtil.java)
java
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayInputStream;
import java.nio.charset.StandardCharsets;
import java.security.KeyFactory;
import java.security.SecureRandom;
import java.security.Signature;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.interfaces.RSAPrivateKey;
import java.security.spec.MGF1ParameterSpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.PSSParameterSpec;
import java.util.Arrays;
import java.util.Base64;
/**
* SUD OpenPaaS API secure communication core utility class
*/
public class SudApiSecurityUtil {
private static final String AES_ALGORITHM = "AES/GCM/NoPadding";
private static final String RSA_PSS_ALGORITHM = "RSASSA-PSS";
private static final int GCM_TAG_LENGTH_BIT = 128;
private static final int GCM_IV_LENGTH_BYTE = 12;
/**
* 1. Request business data encryption (AES-256-GCM)
*/
public static JsonObject encryptRequest(String urlPath, String appId, String keySn, String symmetricKeyBase64, JsonObject reqData) throws Exception {
long timestamp = System.currentTimeMillis() / 1000;
String nonce = generateNonce();
// Fill in the security check fields
reqData.addProperty("_n", nonce);
reqData.addProperty("_appid", appId);
reqData.addProperty("_timestamp", timestamp);
String plaintext = reqData.toString();
// Concatenate AAD: urlpath|appid|timestamp|sn
String aad = String.join("|", urlPath, appId, String.valueOf(timestamp), keySn);
byte[] keyBytes = Base64.getDecoder().decode(symmetricKeyBase64);
byte[] ivBytes = generateRandomBytes(GCM_IV_LENGTH_BYTE);
byte[] aadBytes = aad.getBytes(StandardCharsets.UTF_8);
byte[] plaintextBytes = plaintext.getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
GCMParameterSpec parameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH_BIT, ivBytes);
cipher.init(Cipher.ENCRYPT_MODE, keySpec, parameterSpec);
cipher.updateAAD(aadBytes);
// Java doFinal outputs cipherText + authTag
byte[] ciphertextWithTag = cipher.doFinal(plaintextBytes);
// Separate the ciphertext and the AuthTag (last 16 bytes)
int tagLength = GCM_TAG_LENGTH_BIT / 8;
byte[] ciphertext = Arrays.copyOfRange(ciphertextWithTag, 0, ciphertextWithTag.length - tagLength);
byte[] authTag = Arrays.copyOfRange(ciphertextWithTag, ciphertextWithTag.length - tagLength, ciphertextWithTag.length);
// Assemble the final request Body
JsonObject httpBody = new JsonObject();
httpBody.addProperty("iv", Base64.getEncoder().encodeToString(ivBytes));
httpBody.addProperty("data", Base64.getEncoder().encodeToString(ciphertext));
httpBody.addProperty("authtag", Base64.getEncoder().encodeToString(authTag));
// Return an object containing the timestamp needed for the HTTP Header and the Body ciphertext
JsonObject result = new JsonObject();
result.addProperty("req_ts", timestamp);
result.addProperty("req_data", httpBody.toString());
return result;
}
/**
* 2. Request message signing (RSA-PSS)
*/
public static String signRequest(String urlPath, String appId, long timestamp, String reqData, String privateKeyPem) throws Exception {
// Concatenate strictly in order; String.join guarantees there is absolutely no extra trailing \n
String payload = String.join("\n", urlPath, appId, String.valueOf(timestamp), reqData);
byte[] dataBuffer = payload.getBytes(StandardCharsets.UTF_8);
// Parse the PKCS#8 format private key
String privateKeyBase64 = privateKeyPem
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", "");
byte[] decodedKey = Base64.getDecoder().decode(privateKeyBase64);
PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
RSAPrivateKey privateKey = (RSAPrivateKey) KeyFactory.getInstance("RSA").generatePrivate(keySpec);
// Configure PSS signing parameters (salt length 32, aligned with SHA256)
Signature signature = Signature.getInstance(RSA_PSS_ALGORITHM);
PSSParameterSpec pssSpec = new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1);
signature.setParameter(pssSpec);
signature.initSign(privateKey);
signature.update(dataBuffer);
byte[] sigBuffer = signature.sign();
return Base64.getEncoder().encodeToString(sigBuffer);
}
/**
* 3. Response message signature verification (RSA-PSS)
*/
public static boolean verifyResponseSignature(String urlPath, String expectedAppId, String localCertSn, String platformCertPem,
String respAppId, long respTs, String respSn, String respSig,
String respDeprecatedSn, String respDeprecatedSig, String respData) throws Exception {
// Basic security check: AppId match
if (!expectedAppId.equals(respAppId)) {
return false;
}
// Certificate serial number matching and smooth rotation support
String signatureBase64;
if (localCertSn.equals(respSn)) {
signatureBase64 = respSig;
} else if (respDeprecatedSn != null && localCertSn.equals(respDeprecatedSn)) {
signatureBase64 = (respDeprecatedSig != null && !respDeprecatedSig.isEmpty()) ? respDeprecatedSig : respSig;
} else {
return false; // Certificate serial number mismatch
}
// Concatenate the string to be verified
String payload = String.join("\n", urlPath, respAppId, String.valueOf(respTs), respData);
byte[] dataBuffer = payload.getBytes(StandardCharsets.UTF_8);
// Parse the X.509 certificate
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64.getDecoder().decode(platformCertPem));
X509Certificate certificate = (X509Certificate) certFactory.generateCertificate(inputStream);
// Configure PSS verification parameters
Signature verifier = Signature.getInstance(RSA_PSS_ALGORITHM);
PSSParameterSpec pssSpec = new PSSParameterSpec("SHA-256", "MGF1", MGF1ParameterSpec.SHA256, 32, 1);
verifier.setParameter(pssSpec);
verifier.initVerify(certificate);
verifier.update(dataBuffer);
byte[] sigBuffer = Base64.getDecoder().decode(signatureBase64);
return verifier.verify(sigBuffer);
}
/**
* 4. Response ciphertext decryption (AES-256-GCM)
*/
public static JsonObject decryptResponse(String urlPath, String appId, long respTs, String keySn, String symmetricKeyBase64, String respDataStr) throws Exception {
JsonObject respDataObj = JsonParser.parseString(respDataStr).getAsJsonObject();
String iv = respDataObj.get("iv").getAsString();
String data = respDataObj.get("data").getAsString();
String authTag = respDataObj.get("authtag").getAsString();
// Concatenate AAD
String aad = String.join("|", urlPath, appId, String.valueOf(respTs), keySn);
byte[] dataBytes = Base64.getDecoder().decode(data);
byte[] authTagBytes = Base64.getDecoder().decode(authTag);
// Concatenate the ciphertext and the AuthTag for the Cipher to process
byte[] combinedData = new byte[dataBytes.length + authTagBytes.length];
System.arraycopy(dataBytes, 0, combinedData, 0, dataBytes.length);
System.arraycopy(authTagBytes, 0, combinedData, dataBytes.length, authTagBytes.length);
byte[] keyBytes = Base64.getDecoder().decode(symmetricKeyBase64);
byte[] ivBytes = Base64.getDecoder().decode(iv);
byte[] aadBytes = aad.getBytes(StandardCharsets.UTF_8);
Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
GCMParameterSpec parameterSpec = new GCMParameterSpec(GCM_TAG_LENGTH_BIT, ivBytes);
cipher.init(Cipher.DECRYPT_MODE, keySpec, parameterSpec);
cipher.updateAAD(aadBytes);
byte[] decryptedBytes = cipher.doFinal(combinedData); // Internally verifies the AuthTag automatically
String decryptedData = new String(decryptedBytes, StandardCharsets.UTF_8);
JsonObject realResp = JsonParser.parseString(decryptedData).getAsJsonObject();
// Strongly validate the security fields inside the plaintext
if (!appId.equals(realResp.get("_appid").getAsString()) || respTs != realResp.get("_timestamp").getAsLong()) {
throw new SecurityException("Security field validation failed: the _appid or _timestamp inside the response plaintext does not match the external one");
}
return realResp;
}
/* ================= Helper methods ================= */
private static String generateNonce() {
byte[] nonce = generateRandomBytes(16);
return Base64.getEncoder().encodeToString(nonce).replace("=", "");
}
private static byte[] generateRandomBytes(int length) {
byte[] bytes = new byte[length];
new SecureRandom().nextBytes(bytes);
return bytes;
}
}2. Business Invocation Demo (SudApiDemo.java)
java
import com.google.gson.JsonObject;
public class SudApiDemo {
// Simulated global application configuration
private static final String APP_ID = "cp_10010";
private static final String URL_PATH = "https://api.sud.com/v1/game/login";
private static final String SYM_KEY_SN = "key_v1";
private static final String SYM_KEY = "otUpngOjU+nVQaWJIC3D/yMLV17RKaP6t4Ot9tbnzLY=";
private static final String PRIVATE_KEY_PEM = "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANB... (your complete private key) ...V6W6w=\n-----END PRIVATE KEY-----";
private static final String PLATFORM_CERT_SN = "sud_cert_v1";
private static final String PLATFORM_CERT_PEM = "-----BEGIN CERTIFICATE-----\nMIID0jCCArqgAw... (SUD platform public key certificate) ...Q==\n-----END CERTIFICATE-----";
public static void main(String[] args) {
try {
System.out.println("=== 1. Send request: encrypt and sign business data ===");
// Prepare the raw business request parameters
JsonObject bizReq = new JsonObject();
bizReq.addProperty("appid", APP_ID);
bizReq.addProperty("sud_uid", "user_889900");
bizReq.addProperty("scene", 0);
// Perform encryption
JsonObject encResult = SudApiSecurityUtil.encryptRequest(URL_PATH, APP_ID, SYM_KEY_SN, SYM_KEY, bizReq);
long reqTimestamp = encResult.get("req_ts").getAsLong();
String reqBodyData = encResult.get("req_data").getAsString();
// Perform signing
String reqSignature = SudApiSecurityUtil.signRequest(URL_PATH, APP_ID, reqTimestamp, reqBodyData, PRIVATE_KEY_PEM);
System.out.println("HTTP Header X-Sud-Timestamp: " + reqTimestamp);
System.out.println("HTTP Header X-Sud-Signature: " + reqSignature);
System.out.println("HTTP Body: " + reqBodyData);
System.out.println("\n=== 2. Receive response: verify signature and decrypt ciphertext ===");
// Simulate the Header and Body obtained from the HTTP response interceptor
long respTimestamp = reqTimestamp; // Ideally the response timestamp is close to the request
String respHeaderAppId = APP_ID;
String respHeaderSn = PLATFORM_CERT_SN;
String respHeaderSig = "Ht0VfQkkEweJ4hU266C14... (assumed signature string)";
String respBodyData = "{\"iv\":\"r2WDQt56rEAmMuoR\",\"data\":\"HExs...\",\"authtag\":\"z2BF...\"}";
// Perform response signature verification
boolean isSigValid = SudApiSecurityUtil.verifyResponseSignature(
URL_PATH, APP_ID, PLATFORM_CERT_SN, PLATFORM_CERT_PEM,
respHeaderAppId, respTimestamp, respHeaderSn, respHeaderSig,
null, null, respBodyData
);
if (isSigValid) {
System.out.println("Response signature verification succeeded!");
// Perform decryption
JsonObject decryptedBizData = SudApiSecurityUtil.decryptResponse(URL_PATH, APP_ID, respTimestamp, SYM_KEY_SN, SYM_KEY, respBodyData);
System.out.println("Response decryption succeeded, business data: " + decryptedBizData.toString());
} else {
System.err.println("Response signature verification failed, discarding the message!");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}