签名生成

下面代码中的CLIENT_ID和CLIENT_SECRET值由用户中心统一分配。调用signQuery方法就会给请求url的query部分加上client_id, ts, sign参数。比如:

String getUrl = "https://uc.ms.casicloud.com/1/user/get?" + SignUtil.signQuery("mobile=13510101010");
String updateUrl = "https://uc.ms.casicloud.com/1/user/update?" + SignUtil.signQuery("");
public class SignUtil {
    private final static String CLIENT_ID = "";
    private final static String CLIENT_SECRET = "";
    public static String signQuery(String query) throws Exception {
        StringBuilder builder = new StringBuilder();
        if(StringUtils.isNotEmpty(query)) {
            builder.append(query);
            builder.append("&");
        }
        builder.append("client_id=").append(CLIENT_ID);
        builder.append("&ts=").append(System.currentTimeMillis());
        builder.append("&sign=").append(getSign(queryToMap(builder.toString()), CLIENT_SECRET));
        return builder.toString();
    }

    private static String getSign(Map params, String clientSecret) {
        if(StringUtils.isEmpty(clientSecret) || params == null || params.size() == 0)
            return "";
        List paramNames = new ArrayList<>(params.keySet());
        Collections.sort(paramNames);
        StringBuilder builder = new StringBuilder();
        for(String name : paramNames) {
            builder.append(name);
            builder.append("=");
            builder.append(params.get(name));
        }
        builder.append(clientSecret);
        try {
            return md5(builder.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return "";
    }

    private static Map queryToMap(String query) {
        Map map = new HashMap<>();
        if(StringUtils.isEmpty(query))
            return map;
        String[] array = query.split("&");
        for(String item : array) {
            String[] p = item.split("=");
            if(p.length == 2)
                map.put(p[0], p[1]);
        }
        return map;
    }

    private static String md5(String data) throws NoSuchAlgorithmException {
        MessageDigest m = MessageDigest.getInstance("MD5");
        m.update(data.getBytes(Charset.forName("UTF-8")));
        byte[] digest = m.digest();
        BigInteger bigInt = new BigInteger(1, digest);
        String result = bigInt.toString(16);
        if (result.length() < 32) {
            StringBuffer buffer = new StringBuffer(result);
            while (buffer.length() < 32) {
                buffer.insert(0, '0');
            }
            result = buffer.toString();
        }
        return result;
    }
}