· 5 years ago · Jul 09, 2020, 04:40 AM
1/**
2 * Sign the API request with body.
3 */
4 public static String signApiRequest(Map<String, String> params, String body, String appSecret, String routeName) throws IOException {
5 // first: sort all text parameters
6 String[] keys = params.keySet().toArray(new String[0]);
7 Arrays.sort(keys);
8
9 // second: connect all text parameters with key and value
10 StringBuilder query = new StringBuilder();
11 query.append(routeName);
12 for (String key : keys) {
13 String value = params.get(key);
14 if (areNotEmpty(key, value)) {
15 query.append(key).append(value);
16 }
17 }
18
19 // third:put the body to the end
20 if (body != null) {
21 query.append(body);
22 }
23
24 // next : sign the whole request
25 byte[] bytes = null;
26
27 bytes = encryptHMACSHA256(query.toString(), appSecret);
28
29 // finally : transfer sign result from binary to upper hex string
30 return byte2hex(bytes);
31 }
32
33
34 private static byte[] encryptHMACSHA256(String data, String secret) throws IOException {
35 byte[] bytes = null;
36 try {
37 SecretKey secretKey = new SecretKeySpec(secret.getBytes(Constants.CHARSET_UTF8), Constants.SIGN_METHOD_HMAC_SHA256);
38 Mac mac = Mac.getInstance(secretKey.getAlgorithm());
39 mac.init(secretKey);
40 bytes = mac.doFinal(data.getBytes(Constants.CHARSET_UTF8));
41 } catch (GeneralSecurityException gse) {
42 throw new IOException(gse.toString());
43 }
44 return bytes;
45 }
46
47 /**
48 * Transfer binary array to HEX string.
49 */
50 public static String byte2hex(byte[] bytes) {
51 StringBuilder sign = new StringBuilder();
52 for (int i = 0; i < bytes.length; i++) {
53 String hex = Integer.toHexString(bytes[i] & 0xFF);
54 if (hex.length() == 1) {
55 sign.append("0");
56 }
57 sign.append(hex.toUpperCase());
58 }
59 return sign.toString();
60 }