1 package com.kdt.api; 2 3 import java.io.UnsupportedEncodingException; 4 import java.security.MessageDigest; 5 import java.security.NoSuchAlgorithmException; 6 import java.util.ArrayList; 7 import java.util.Collections; 8 import java.util.HashMap; 9 import java.util.List; 10 11 public class KdtApiProtocol { 12 public static final String APP_ID_KEY = "app_id"; 13 public static final String METHOD_KEY = "method"; 14 public static final String TIMESTAMP_KEY = "timestamp"; 15 public static final String FORMAT_KEY = "format"; 16 public static final String VERSION_KEY = "v"; 17 public static final String SIGN_KEY = "sign"; 18 public static final String SIGN_METHOD_KEY = "sign_method"; 19 20 public static final int ALLOWED_DEVIATE_SECONDS = 600; 21 22 public static final int ERR_SYSTEM = -1; 23 public static final int ERR_INVALID_APP_ID = 40001; 24 public static final int ERR_INVALID_APP = 40002; 25 public static final int ERR_INVALID_TIMESTAMP = 40003; 26 public static final int ERR_EMPTY_SIGNATURE = 40004; 27 public static final int ERR_INVALID_SIGNATURE = 40005; 28 public static final int ERR_INVALID_METHOD_NAME = 40006; 29 public static final int ERR_INVALID_METHOD = 40007; 30 public static final int ERR_INVALID_TEAM = 40008; 31 public static final int ERR_PARAMETER = 41000; 32 public static final int ERR_LOGIC = 50000; 33 34 public static String sign(String appSecret, HashMap<String,String> parames){ 35 Object[] keyArray = parames.keySet().toArray(); 36 List<String> keyList = new ArrayList<String>(); 37 for(int i = 0; i < keyArray.length; i++){ 38 keyList.add((String)keyArray[i]); 39 } 40 Collections.sort(keyList); 41 String signContent = appSecret; 42 43 for (String key : keyList) { 44 signContent += (key + parames.get(key)); 45 } 46 signContent += appSecret; 47 return hash(signContent); 48 } 49 50 private static String hash(String signContent){ 51 String hashResult = ""; 52 try { 53 MessageDigest md = MessageDigest.getInstance("MD5"); 54 md.update(signContent.getBytes("UTF-8")); 55 byte byteData[] = md.digest(); 56 StringBuffer sb = new StringBuffer(); 57 for(int i = 0; i < byteData.length; i++){ 58 sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1)); 59 } 60 hashResult = sb.toString().toLowerCase(); 61 } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { 62 } 63 64 return hashResult; 65 } 66 }