案例背景,第三方API,使用实体类的参数加上时间戳,key,按照字母顺序排列,拼接成字符串,再对次字符串进行MD5计算,得出的结果就是sign,服务端也根据该方法进行sign计算,
此处以HashMap为例
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
public class Test23 {
public static void main(String[] args) throws UnsupportedEncodingException {
HashMap<String, String> hashMap=new HashMap<String, String>();
hashMap.put("a","123");
hashMap.put("b","234");
hashMap.put("c","345");
StringBuilder stringBuilder = new StringBuilder();
Set<String> strings = hashMap.keySet();
List<String> collect = strings.stream().sorted().collect(Collectors.toList());
for (int i = 0; i < collect.size(); i++) {
String s = collect.get(i);
String value = hashMap.get(s);
//对中文进行URL编码
value = URLEncoder.encode(value, String.valueOf(StandardCharsets.UTF_8));
if (i == 0) {
stringBuilder.append(s).append("=").append(value);
} else {
stringBuilder.append("&").append(s).append("=").append(value);
}
}
System.out.println(stringBuilder);
String md5 = getMD5(stringBuilder.toString());
System.out.println(md5);
}
public static String getMD5(String s) {
char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
try {
byte[] btInput = s.getBytes(StandardCharsets.UTF_8);
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
int j = md.length;
char[] str = new char[j * 2];
int k = 0;
for (byte byte0 : md) {
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}