package com.**.**.utils;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class ApiSignatureUtil {
private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
*
* 功能描述: <br>
* 获取签名,会将paramMap里的数据和secretKey组成name1=value1&name2=value2格式的数据后进行md5算法加签名
* @param appSecret
* @param paramMap 调用api时要传递参数组成的map,不可为null
* @return
* @since V1.0.0
*/
public static String getSignature(String appSecret,final Map<String, String> paramMap){
//复制一份数据,防止源数据信息被修改
Map<String,String> newParamMap = new HashMap<String,String>(paramMap);
newParamMap.put("appSecret", appSecret);
String signature = md5Hex(getSortString(newParamMap).getBytes());
return signature;
}
/**
*
* 功能描述: <br>
* 获取排序后的字符串信息
*
* @param paramMap 参数组成的map
* @return
* @since V1.0.0
*/
private static String getSortString(Map<String, String> paramMap) {
// 将map中的参数拼接成name=value的形式
List<String> paramList = new ArrayList<String>(paramMap.size());
for (String key : paramMap.keySet()) {
String value = paramMap.get(key);
if(null!=value&&!value.isEmpty()){
paramList.add(key + "=" + paramMap.get(key));
}
}
// 将结果排序后拼接成name1=value1&name2=value2的形式
Collections.sort(paramList);
StringBuilder sb = new StringBuilder();
for (String str : paramList) {
sb.append(str).append("&");
}
return sb.toString();
}
public static String md5Hex(byte[] data) {
return encodeHexString(md5(data));
}
public static String encodeHexString(byte[] data) {
return new String(encodeHex(data));
}
protected static char[] encodeHex(byte[] data) {
char[] toDigits = DIGITS_LOWER;
int l = data.length;
char[] out = new char[l << 1];
// two characters form the hex value.
for (int i = 0, j = 0; i < l; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
return out;
}
public static byte[] md5(byte[] data) {
return getMd5Digest().digest(data);
}
private static MessageDigest getDigest(String algorithm) {
try {
return MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e.getMessage());
}
}
private static MessageDigest getMd5Digest() {
return getDigest("MD5");
}
}