工具类
import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
/**
* @author wangwei
* @version v1.0.0
* @description 签名
* @date 2019-01-12
*/
@RefreshScope
public class SignUtil {
private static Logger logger = LoggerFactory.getLogger(SignUtil.class);
public static SignUtil signUtil;
// 对外的密钥
// @Value("${sign-secret-secret}")
public String secretkey = "mysecret123456";
/** 加密密钥 */
//@Value("${sign.secret.appkey}")
public String appkey = "mykey123456";
// 间隔时间
//@Value("${sign.timeout}")
public int timeout = 1 * 30 * 1000;
/** 加密密钥 */
// private final static String APP_KEY = "mykey123456";
// public final static String SECRET_KEY = "mysecret123456";
/** 字符编码 */
private final static String INPUT_CHARSET = "UTF-8";
// /** 超时时间 */
// private final static int TIME_OUT = 1 * 30 * 1000;
public static SignUtil getInstance() {
if(signUtil == null) {
signUtil = new SignUtil();
}
return signUtil;
}
/**
* 请求参数Map转换验证Map
* @param requestParams 请求参数Map
* @param charset 是否要转utf8编码
* @return
* @throws UnsupportedEncodingException
*/
public static Map toVerifyMap(Map requestParams, boolean charset) {
Map params = new HashMap<>();
for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
String name = (String) iter.next();
String[] values = requestParams.get(name);
String valueStr = "";
for (int i = 0; i < values.length; i++) {
valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
}
//乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
if(charset)
valueStr = getContentString(valueStr, INPUT_CHARSET);
params.put(name, valueStr);
}
return params;
}
/**
* 除去数组中的空值和签名参数
* @param sArray 签名参数组
* @return 去掉空值与签名参数后的新签名参数组
*/
public static Map paraFilter(Map sArray) {
Map result = new HashMap<>();
if (sArray == null || sArray.size() <= 0) {
return result;
}
for (String key : sArray.keySet()) {
String value = sArray.get(key);
if (value == null || value.equals("") || key.equalsIgnoreCase("sign")) {
// || key.equalsIgnoreCase("time") 这里可以将时间参数分离,因为时间参数为毫秒 接口传递需要时间,如果毫秒数一旦超过,则签名验证失败,后面有判断签名时间在合理范围内
continue;
}
result.put(key, value);
}
return result;
}
/**
* 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param params 需要排序并参与字符拼接的参数组
* @return 拼接后字符串
*/
public static String createLinkString(Map params) {
return createLinkString(params, false);
}
/**
* 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
* @param params 需要排序并参与字符拼接的参数组
* @param encode 是否需要UrlEncode
* @return 拼接后字符串
*/
public static String createLinkString(Map params, boolean encode) {
List keys = new ArrayList<>(params.keySet());
Collections.sort(keys);
String prestr = "";
for (int i = 0; i < keys.size(); i++) {
String key = keys.get(i);
String value = params.get(key);
if (encode)
value = urlEncode(value, INPUT_CHARSET);
if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符
prestr = prestr + key + "=" + value;
} else {
prestr = prestr + key + "=" + value + "&";
}
}
return prestr;
}
/**
* 编码转换
* @param content
* @param charset
* @return
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
/**
* 编码转换
* @param content
* @param charset
* @return
*/
private static String getContentString(String content, String charset) {
if (charset == null || "".equals(charset)) {
return new String(content.getBytes());
}
try {
return new String(content.getBytes("ISO-8859-1"), charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
/**
* URL转码
* @param content
* @param charset
* @return
*/
private static String urlEncode(String content, String charset) {
try {
return URLEncoder.encode(content, charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
//TODO 签名
/**
* 生成要请求的签名参数数组
* @param sParaTemp 需要签名的参数Map
* @return 要请求的签名参数数组
*/
public static Map signMap(Map sParaTemp) {
//请求参数Map转换验证Map,并生成要请求的签名参数数组
return SignUtil.getInstance().sign(toVerifyMap(sParaTemp, false));
}
/**
* 生成要请求的签名参数数组
* @param sParaTemp 需要签名的参数
* @return 要请求的签名参数数组
*/
public Map sign(Map sParaTemp) {
//时间戳加入签名参数组中
sParaTemp.put("timestamp", String.valueOf(System.currentTimeMillis()));
//除去数组中的空值和签名参数
Map sPara = paraFilter(sParaTemp);
//把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串
String prestr = createLinkString(sPara);
//生成签名结果
String mysign = DigestUtils.md5Hex(getContentBytes(prestr + appkey, INPUT_CHARSET));
//签名结果加入请求提交参数组中
sPara.put("sign", mysign);
return sPara;
}
public static String getSignStr(Map sParaTemp) {
return SignUtil.getInstance().sign(sParaTemp).get("sign");
}
/**
* 生成要请求的签名参数字符串“参数=参数值”&链接
* @param sParaTemp 需要签名的参数Map
* @return 请求的签名参数字符串
*/
public static String signStringMap(Map sParaTemp) {
//生成要请求的签名参数数组
Map sign = signMap(sParaTemp);
//生成要请求的签名参数字符串“参数=参数值”&链接
return createLinkString(sign, true);
}
/**
* 生成要请求的签名参数字符串“参数=参数值”&链接
* @param sParaTemp 需要签名的参数
* @return
*/
public static String signString(Map sParaTemp) {
//生成要请求的签名参数数组
Map sign = SignUtil.getInstance().sign(sParaTemp);
//生成要请求的签名参数字符串“参数=参数值”&链接
return createLinkString(sign, true);
}
//TODO 验证签名
/**
* 根据反馈回来的信息,生成签名结果
* @param paramsMap 通知返回来的请求参数Map
* @return 验证结果
*/
public static boolean verifyMap(Map paramsMap) {
//请求参数Map转换验证Map,并根据反馈回来的信息,生成签名结果
return SignUtil.getInstance().verify(toVerifyMap(paramsMap, false));
}
/**
* 根据反馈回来的信息,生成签名结果
* @param params 通知返回来的参数数组
* @return 验证结果
*/
public boolean verify(Map params) {
String sign = "";
if (params.get("sign") != null) {
sign = params.get("sign");
}else {
logger.info("sign is null");
return false;
}
String timestamp = "";
if (params.get("time") != null) {
timestamp = params.get("time");
}else {
return false;
}
//过滤空值、sign
Map sParaNew = paraFilter(params);
//获取待签名字符串
String preSignStr = createLinkString(sParaNew);
//获得签名验证结果
String mysign = DigestUtils.md5Hex(getContentBytes(preSignStr + appkey, INPUT_CHARSET));
if (mysign.equals(sign)) {
//是否超时
long curr = System.currentTimeMillis();
if ((curr - Long.valueOf(timestamp)) > timeout){
logger.info("api is time out" + curr);
return false;
}
return true;
} else {
return false;
}
}
}
接口控制器调用
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* @author wangwei
* @version v1.0.0
* @description 测试签名用
* @date 2019-01-12
*/
@RestController
@RequestMapping("/api/open/rest/{version}/signtest")
public class SignTestController {
/**
* 模拟客户端请求API接口
* @param request
* @return
*/
@RequestMapping("send")
public String send(HttpServletRequest request){
Map param = new HashMap<>();
param.put("userId","9527");
param.put("amount","9.99");
param.put("productId","9885544154");
param.put("secretKey","mysecret123456");
try {
String postResult = HttpClient.get("http://127.0.0.1:8773/api/open/v1.0.1/ad/list", SignUtil.getInstance().sign(param));
return postResult;
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
/**
* showdoc
* @catalog v1.0.1/测试相关
* @title 模拟服务的API接口
* @description 模拟服务的API接口
* @method post
* @url /api/open/rest/v1.0.1/signtest/checkSign
* @param secretKey 必选 string 秘钥
* @param time 必选 string 请求时间戳
* @param sign 必选 string 参数MD5签名
* @return {"status":"200","message":"请求成功","data":,"page":null,"ext":null}
* @return_param code int 验证码
* @return_param status string 状态
* @remark 这里是备注信息
* @number 99
*/
@RequestMapping("checkSign")
public Resp checkSign(HttpServletRequest request){
//从request中获取参数列表,转成map
Map map = SignUtil.toVerifyMap(request.getParameterMap(),false);
String secretKey = map.get("secretKey");
if (StringUtils.isEmpty(secretKey) || !map.get("secretKey").equals(SignUtil.getInstance().secretkey)){
System.out.println("secretKey is err");
return Resp.fail(ErrorCode.CODE_431);
}
if (SignUtil.getInstance().verify(map)){
return Resp.success();
}else {
return Resp.fail(ErrorCode.CODE_430);
}
}
}
签名验证过滤器
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;
/**
* @author wangwei
* @version v1.0.0
* @description 签名过滤器, 签名不拦截open下的接口
* @date 2019-01-12
*/
@Component
@WebFilter(filterName="SignFilter", urlPatterns="/*")
@RefreshScope
public class SignFilter implements Filter {
@Value("${version}")
private String version;
@Override
public void init(javax.servlet.FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
String path = request.getRequestURI();
if(path.indexOf("/api/open/")> -1 ){
filterChain.doFilter(servletRequest, servletResponse);
return;
}
Map map = SignUtil.toVerifyMap(request.getParameterMap(),false);
String secretKey = map.get("secretKey");
if (StringUtils.isEmpty(secretKey) || !map.get("secretKey").equals(SignUtil.getInstance().secretkey)){
System.out.println("secretKey is err");
PrintWriter writer = null;
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html; charset=utf-8");
try {
writer = servletResponse.getWriter();
String userJson = "{\"code\":\" "+ ErrorCode.CODE_431.getCode() +"\", \"message\": \""+ ErrorCode.CODE_431.getMessage() +"\"}";
writer.print(userJson);
} catch (IOException e1) {
} finally {
if (writer != null)
writer.close();
}
}
if (SignUtil.getInstance().verify(map)){
// 签名成功
filterChain.doFilter(servletRequest, servletResponse);
return;
}else {
PrintWriter writer = null;
servletResponse.setCharacterEncoding("UTF-8");
servletResponse.setContentType("text/html; charset=utf-8");
try {
writer = servletResponse.getWriter();
String userJson = "{\"code\":\" "+ ErrorCode.CODE_430.getCode() +"\", \"message\": \""+ ErrorCode.CODE_430.getMessage() +"\"}";
writer.print(userJson);
} catch (IOException e1) {
} finally {
if (writer != null)
writer.close();
}
}
}
@Override
public void destroy() {
}
}