To ensure HTTPS-based transmission security and prevent request parameters from being tampered with, an app must include a signature string of the request parameters – cpSign – in the sign-in signature verification API that is called. The signature string is used by Huawei game server to verify the request parameters. The rules for generating a signature string are as follows:
private static String format(Map<String, String> params)
{
StringBuffer base = new StringBuffer();
Map<String, String> tempMap = new TreeMap<String, String>(params);
// Obtain the basic string for calculating nsp_key.
try
{
for (Map.Entry<String, String> entry : tempMap.entrySet())
{
String k = entry.getKey();
String v = entry.getValue();
base.append(k).append("=").append(URLEncoder.encode(v, "UTF-8")).append("&");
}
}
catch (UnsupportedEncodingException e)
{
System.out.println("Encode parameters failed.");
e.printStackTrace();
}
String body = base.toString().substring(0, base.toString().length() - 1);
// Convert spaces and asterisks.
body = body.replaceAll("\\+", "%20").replaceAll("\\*", "%2A");
return body;
}
If your game private key must be stored on the app server, the signature string must be generated on the server.
Java sample code:
private static String generateCPSign(Map<String,String> requestParams,final String cpAuthKey)
{
// Sort the queried string in the message body in alphabetical order and URL encode it.
String baseStr = format(requestParams);
// Sign the encoded request string using your private key for signature.
String cpSign = sign(baseStr.getBytes(Charset.forName("UTF-8")), cpAuthKey);
return cpSign;
}
private static String sign(byte[] data, String privateKey)
{
try
{
byte[] e = Base64.decodeBase64(privateKey);
PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(e);
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
Signature signature = Signature.getInstance("SHA256WithRSA");
signature.initSign(privateK);
signature.update(data);
String signs = Base64.encodeBase64String(signature.sign());
return signs;
}
catch (Exception var)
{
System.out.println("SignUtil.sign error." + var);
return "";
}
}