说明:在实际开发中,经常会用到一些第三方接口需要去对参数按顺序进行拼接生成签名进行鉴权校验,这里我把公共的代码贴出来,以供大家参考。
public static String generateSignature(Map<String, String> data) throws Exception {
Set<String> keySet = data.keySet();
String[] keyArray = keySet.toArray(new String[keySet.size()]);
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyArray.length; i++) {
// 参数值为空,则不参与签名
if (data.get(keyArray[i]).trim().length() <= 0 || keyArray[i].equals("sign")) {
continue;
}
sb.append(keyArray[i]).append("=").append(data.get(keyArray[i]).trim());
if (i < keyArray.length - 1) {
sb.append("&");
}
}
return MD5(sb.toString());
}
/**
* 生成 MD5
*
* @param data 待处理数据
* @return MD5结果
*/
public static String MD5(String data) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] array = md.digest(data.getBytes("UTF-8"));
StringBuilder sb = new StringBuilder();
for (byte item : array) {
sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString().toUpperCase();
}