package Utils; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.TreeMap; import com.alibaba.fastjson.JSONObject; public class signUtil { /** * 按照字段名的ASCII 码从小到大排序,并且使用”&”作为分隔符,组成字符串 * 对组装好的参数添加双方约好的密钥Key,进行MD5加密,并将签名都转换为小写字母 * @param params * @param key * @return */ public static JSONObject createSign(Map params, String key) { StringBuffer sb = new StringBuffer(); StringBuffer sbkey = new StringBuffer(); // entrySet 所有参与传参的参数按照accsii排序(升序) Set es = params.entrySet(); Iterator it = es.iterator(); while (it.hasNext()) { Map.Entry entry = (Map.Entry) it.next(); String k = (String) entry.getKey(); Object v = entry.getValue(); //空值不传递,不参与签名组串 if (null != v && !"".equals(v)) { sb.append(k + "=" + v + "&"); } } JSONObject json = new JSONObject(); json.put("sb", sb.toString()); sbkey = sb.append("key=" + key); System.out.println("请求参数+key---> : "+sbkey); //MD5加密,结果转换为小写字符 String sign = encode(sbkey.toString()).toLowerCase(); json.put("sign", sign.toString()); return json; } /** * MD5加密 * @param str * @return */ public static String encode(String str) { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); digest.update(str.getBytes()); return new BigInteger(1, digest.digest()).toString(16); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); return null; } } /** * StringToMap * @param str * @return */ public static SortedMap<Object, Object> StringToMap(String str){ String[] strs=str.split("&"); SortedMap<Object, Object> map = new TreeMap<>(); for (String string : strs) { String key=string.split("=")[0]; String value=string.split("=")[1]; map.put(key, value); } return map; } public static void main(String[] args) { String key = "1234"; SortedMap<Object, Object> map = new TreeMap<>(); map.put("user", "1"); map.put("time", "2018-09-09 23:31:00"); map.put("number", "3000000000000"); JSONObject json = createSign(map,key); String sb = json.containsKey("sb")?json.getString("sb"):""; String sign = json.containsKey("sign")?json.getString("sign"):""; String url = sb+"sign="+sign; System.out.println("url---> : "+url); } }
针对同一字符串加密结果不通的问题,需要根据运行环境指定字符集:
/**
* MD5加密
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static String encode(String str) throws UnsupportedEncodingException {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.update(str.getBytes("UTF-8"));
return new BigInteger(1, digest.digest()).toString(16);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
}
验证地址:http://tool.chinaz.com/Tools/md5.aspx