我们项目要给别的系统的接口推送数据安全要求要求加密传输,要求如下;
sign生成规则
key: 00000000000
secret: 123123
(1)把参数(Map<String,Object>类型)按字典排序 ksort 得到param_str
(2)参数map中加入key ,然后按字典排序转化为字符串用&连接,md5加密secret得到md5_secret_str
(3)拼接param_str和 md5_secret_str,然后对拼接出来的字符串md5加密
(4)对最终加密串转化为大写
注:空值不参与加密、sign/sign_type不参与加密,secret不作为参数传递,所以在(1)中的参数不包含secret
传参为param_str+"&key="+UtilKsort.KEY+"&sign="+sign
接收参数的接口根据param_str也生成sign和接收到的sign比对,再比对key如果都相等则通过
工具类如下:
public class UtilKsort {
public final static Logger logger = LoggerFactory.getLogger(UtilKsort.class);
public final static String KEY="00000000000";
public final static String SECRET="123123";
//dizi
//public final static String BASEURL="";
/**
* 使用 Map按key进行排序
* @param map
* @return
*/
public static Map<String, Object> sortMapByKey(Map<String,Object> map) {
if (map == null || map.isEmpty()) {
return null;
}
Map<String, Object> sortMap = new TreeMap<String, Object>(
new MapKeyComparator());
sortMap.putAll(map);
return sortMap;
}
/**
*
* map转str
* @param map
* @return
* @throws UnsupportedEncodingException
*/
public static String getMapToString(Map<String,Object> map) throws UnsupportedEncodingException{
Set<String> keySet = map.keySet();
//将set集合转换为数组
String[] keyArray = keySet.toArray(new String[keySet.size()]);
//给数组排序(升序)
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyArray.length; i++) {
// 参数值为空,则不参与签名 这个方法trim()是去空格
if (map.get(keyArray[i]).toString().length() > 0) {
sb.append(keyArray[i]).append("=").append(URLEncoder.encode(map.get(keyArray[i]).toString(),"UTF-8"));
if(i != keyArray.length-1){
sb.append("&");
}
}
}
return sb.toString();
}
/**
* 得到sign
* @throws UnsupportedEncodingException
*/
public static String MapgetSign(Map<String,Object> map) throws UnsupportedEncodingException{
//二进制图片视频不参与要删除
Set<String> keySet = map.keySet();
map.put("key", KEY);
//将set集合转换为数组
String[] keyArray = keySet.toArray(new String[keySet.size()]);
//给数组排序(升序)
Arrays.sort(keyArray);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < keyArray.length; i++) {
// 参数值为空,则不参与签名 这个方法trim()是去空格
if (map.get(keyArray[i]).toString().trim().length() > 0) {
sb.append(keyArray[i]).append("=").append(URLEncoder.encode(map.get(keyArray[i]).toString().trim(),"UTF-8"));
if(i != keyArray.length-1){
sb.append("&");
}
}
}
//System.out.println(sb);
String secret = DigestUtils.md5Hex(SECRET.getBytes());
String sign=sb.toString()+secret;
//System.out.println(sign);
return DigestUtils.md5Hex(sign.getBytes()).toUpperCase();
}
public static String StringgetSign(String parm){
String secret = DigestUtils.md5Hex(SECRET.getBytes());
String sign=parm+secret;
return DigestUtils.md5Hex(sign.getBytes()).toUpperCase();
}
public static String md5(String text, String key) throws Exception {
//加密后的字符串
String encodeStr=DigestUtils.md5Hex((text + key).getBytes());
System.out.println("MD5加密后的字符串为:encodeStr="+encodeStr);
return encodeStr;
}
/**
* MD5验证方法
*
* @param text 明文
* @param key 密钥
* @param md5 密文
* @return true/false
* @throws Exception
*/
public static boolean verify(String text, String key, String md5) throws Exception {
//根据传入的密钥进行验证
String md5Text = md5(text, key);
if(md5Text.equalsIgnoreCase(md5))
{
System.out.println("MD5验证通过");
return true;
}
return false;
}
public static String request(String httpUrl,String parm) {
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
try {
URL url=new URL(httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置通用的请求属性
// POST方法
connection.setRequestMethod("POST");
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream(), "UTF-8");
out.write(parm);
out.flush();
out.close();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead); sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
} catch (Exception e) {
e.printStackTrace();
return result;
}
return result;
}
}
class MapKeyComparator implements Comparator<String>{
@Override
public int compare(String str1, String str2) {
return str1.compareTo(str2);
}
}
使用类:
String parm=null;
String sign=null;
try {
logger.info(map.toString());//参数
parm = UtilKsort.getMapToString(map);//参数排序
sign = UtilKsort.MapgetSign(map);;//得到sign
BufferedReader reader = null;
String result = null;
StringBuffer sbf = new StringBuffer();
URL url=new URL(UtilKsort.BASEURL+httpUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
// 设置通用的请求属性
// POST方法
connection.setRequestMethod("POST");
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
connection.connect();
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8缂栫爜
out.write(parm+"&key="+UtilKsort.KEY+"&sign="+sign);
out.flush();
out.close();
InputStream is = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String strRead = null;
while ((strRead = reader.readLine()) != null) {
sbf.append(strRead); sbf.append("\r\n");
}
reader.close();
result = sbf.toString();
Map<String, Object> mapres =JSONObject.parseObject(result);
logger.info(result);
if(null!=mapres){
String code =mapres.get("code").toString();
String message =null!=mapres.get("message").toString()?
mapres.get("message").toString():"";
logger.info(code+"----"+message);
}else{
logger.info("推送失败");
}
return returnDate.success(ExceptionEnum.SUCCESS);
} catch (Exception e) {
e.printStackTrace();
logger.info("推送失败");
}