package com.panda.task.common.utils;
import com.google.common.base.Charsets;
import com.google.common.collect.Ordering;
import com.google.common.hash.Hashing;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;
/**
* Created by LeWis on 2018/1/15.
*/
public class SignUtil {
private static Log log = LogFactory.getLog(SignUtil.class);
/**
* 验证签名
*
* @param request 请求
* @param domain 域名如: http://test.xxx.com
* @param secret 密钥
* @return
*/
public static boolean verify(HttpServletRequest request,String domain, String secret) {
//获取所有请求参数
Enumeration<String> paramKeys = request.getParameterNames();
Map<String, String> params = new HashMap<>();
while (paramKeys.hasMoreElements()) {
String key = paramKeys.nextElement();
params.put(key, request.getParameter(key));
}
if (!params.containsKey("sig")) {
return false;
} else {
//获取当前key
String key = params.remove("sig");
//对参数进行加密
String currentKey = sign(domain + request.getRequestURI(), params, secret);
log.info("sig:" + key);
log.info("currentKey:" + currentKey);
//对比
return Objects.equals(key, currentKey);
}
}
//生成签名
private static String sign(String uri, Map<String, String> params, String secret) {
List<String> keys = Ordering.usingToString().sortedCopy(params.keySet());//key排序
StringBuilder sb = new StringBuilder();
sb.append(uri).append("?");
for (String k : keys) {
try {
sb.append(k).append("=").append(URLDecoder.decode(params.get(k), "utf-8")).append("&");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
sb.deleteCharAt(sb.length() - 1);
sb.append(secret);
log.info("参数:" + sb.toString());
return Hashing.md5().hashString(sb, Charsets.UTF_8).toString();
}
}
网友评论