1.获取url链接里面的时间戳和签名
// 时间戳
String timestamp = qpMap.get("timestamp");
// 签名
String sign = qpMap.get("sign");
2.进行校验
// 校验签名前后过期时间
checkSignTime(timestamp);
// 校验签名
checkSign(streamStr, timestamp, sign);
private void checkSignTime(String timestamp) {
if (StringUtils.isBlank(timestamp)) {
//logger.error("{}-鉴权时间戳缺失", MsgCode.SIGN_PARAM_ERROR_CODE);
throw new BusinessException(MsgCode.SIGN_PARAM_ERROR_MSG, MsgCode.SIGN_PARAM_ERROR_CODE);
}
long currentTime = System.currentTimeMillis() / 1000;// 统一都传毫秒
long requestTime = 0;
try {
requestTime = Long.parseLong(timestamp);
} catch (NumberFormatException e) {
//logger.error("{}-鉴权时间戳错误 timestamp:{}", MsgCode.SIGN_PARAM_ERROR_CODE, timestamp);
throw new BusinessException(MsgCode.SIGN_PARAM_ERROR_MSG, MsgCode.SIGN_PARAM_ERROR_CODE);
}
if (Math.abs(currentTime - requestTime) > APPIConstants.Filter.OUT_OF_DATE_TIME_LONG) {
logger.error("{}-签名已过期,服务器当前时间:{}", MsgCode.OUT_OF_DATE_SIGN_CODE, currentTime);
throw new BusinessException(String.format(MsgCode.OUT_OF_DATE_SIGN_MSG, currentTime), MsgCode.OUT_OF_DATE_SIGN_CODE);
}
}
if (StringUtils.isBlank(sign)) {
//logger.error("{}-签名为空", MsgCode.SIGN_PARAM_ERROR_CODE);
throw new BusinessException(MsgCode.SIGN_PARAM_ERROR_MSG, MsgCode.SIGN_PARAM_ERROR_CODE);
}
// 验证签名
streamStr = Base64.encode(streamStr);
if (!SignUtil.checkSign(streamStr, APPIConstants.Filter.key, timestamp, sign)) {
//logger.error("{}-签名错误", MsgCode.SIGN_ERR_CODE);
throw new BusinessException(MsgCode.SIGN_ERR_MSG, MsgCode.SIGN_ERR_CODE);
}
}
验证工具类:
public class SignUtil {
private final static Logger logger = LoggerFactory.getLogger(SignUtil.class);
/**
* @Description 验证签名
* @param content 验签内容
* @param key 签名key值
* @param additionContent 附加的签名信息
* @param sign 待验证的签名
*/
public static boolean checkSign(String content, String key, String additionContent, String sign) {
if (StringUtils.isBlank(sign)) {
return false;
}
String _sign = createSign(content, key, additionContent);
if (sign.equalsIgnoreCase(_sign)) {
return true;
}
logger.error("参数sign:{},验签sign:{}", sign, _sign);
return false;
}
/**
* @Description 生成签名
* @param content 签名内容
* @param key 签名key值
*/
public static String createSign(String content, String key, String additionContent) {
if(StringUtils.isEmpty(additionContent)){
return MD5Util.getMd5(content + key);
}else{
return MD5Util.getMd5(content + key + additionContent);
}
}
}
---------------------
原文:https://blog.csdn.net/riju4713/article/details/81457479