感谢我一位阿里的安全大佬朱哥,在我发第一篇博客的时候进行指点。 我对上一篇的不足之处进行总结一下:
new 拦截器
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import JAVAx.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;
public class MyBetterInterceptor implements HandlerInterceptor {
public static final ThreadLocal<String> local = new ThreadLocal<>();
public static final ThreadLocal<String> localSign = new ThreadLocal<>();
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String sign = request.getHeader("sign");
//这里对应appId,外面可以去数据库查Secret
String appId = request.getHeader("appId");
if (valid(sign) || valid(appId)) {
throw new IllegalAccessException("验签非法");
}
String time = request.getHeader("createTime");
if (valid(time)) {
throw new IllegalAccessException("时间戳为空");
}
long second = DateUtil.between(new Date(), DateUtil.parse(time), DateUnit.MINUTE);
if (!(second <= 30 && DateUtil.compare(new Date(), DateUtil.parse(time)) > 0)) {
throw new IllegalAccessException("非法时间戳");
}
String sb;
if ("POST".equals(request.getMethod())) {
//System.out.println("post参数:" + new String(IoUtil.readBytes(request.getInputStream(), false)));
/*String parameter = new String(IoUtil.readBytes(request.getInputStream(), false));
sb = ParameterUtil.generateSign(ParameterUtil.postParameter(parameter, time));*/
local.set(time);
localSign.set(sign);
return true;
} else {
Map<String, String[]> map = request.getParameterMap();
System.out.println(JSON.toJSONString(map));
if (map == null || map.size() == 0) {
return false;
}
sb = ParameterUtil.generateSign(ParameterUtil.getParameter(map, time));
}
System.out.println("加密混淆之后的字符串:" + sb);
//Todo 去数据库查询appId对应的Sercert,比如这里固定查出来是dajitui
sb = sb + "dajitui";
System.out.println("sign:" + SecureUtil.md5(sb));
if (SecureUtil.md5(sb).equals(sign)) {
return true;
}
return true;
}
private boolean valid(String value) {
return StrUtil.isBlank(value);
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
注意点
1.拦截器:我们只能处理get请求的参数,post的话request只能读取一次,后面无法再读取一遍,我们使用aop去进行验签。 2.加密算法有所改变,添加了Sercert特有的参数,即使appid被别人拿到了,也没有多大影响。
加密处理过程
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import org.Apache.commons.codec.digest.DigestUtils;
import java.util.*;
import java.util.stream.Collectors;
/**
* @author M
*/
public class ParameterUtil {
ParameterUtil() {
}
public static Map<String, Object> getParameter(Map<String, String[]> map, String time) {
if (map == null || map.size() == 0) {
return new HashMap<>(6);
}
Map<String, Object> resultMap = new HashMap<>(map.size());
map.forEach((k, v) -> {
if (v.length == 1) {
resultMap.put(k, v[0]);
} else {
resultMap.put(k, new ArrayList<>(Arrays.asList(v)));
}
});
resultMap.put("time",time);
System.out.println("map:"+ JSON.toJSONString(resultMap));
return resultMap;
}
public static Map<String, Object> postParameter(String msg, String time) {
if (StrUtil.isBlank(msg)) {
return new HashMap<>(6);
}
JSONArray array=new JSONArray(msg);
Map<String, Object> resultMap = new HashMap<>(25);
for(JSONObject object:array.jsonIter()){
for (String s : object.keySet()) {
resultMap.put(s, object.get(s));
}
resultMap.put("time",time);
}
System.out.println("map:"+ JSON.toJSONString(resultMap));
return resultMap;
}
public static final String SEPERATE_CHAR = "#%$";
public static String generateSign(Map<String, Object> param) {
Set<String> keys = param.keySet();
//过滤掉sign,对key进行排序
List<String> sortedKeys = keys.stream().filter(key -> !Objects.equals(key, "sign")).sorted().collect(Collectors.toList());
//加上自定义字符串混淆算法
String calcSign = sortedKeys.stream().map(param::get).map(String::valueOf).collect(Collectors.joining(SEPERATE_CHAR));
//对字符串进行hash
calcSign = DigestUtils.sha1Hex(calcSign);
return calcSign;
}
public static void main(String[] args) {
System.out.println(ParameterUtil.postParameter("{n" +
" "status": "0000",n" +
" "message": "success",n" +
" "data": {n" +
" "title": {n" +
" "id": "001",n" +
" "name" : "白菜"n" +
" },n" +
" "content": [n" +
" {n" +
" "id": "001",n" +
" "value":"你好 白菜"n" +
" },n" +
" {n" +
" "id": "002",n" +
" "value":"你好 萝卜" n" +
" }n" +
" ]n" +
" }n" +
"}",""));
}
}
其中 postParameter是处理post参数,getParameter处理get参数转成Map<String,Object>形式。
generateSign才是真正的大头
public static final String SEPERATE_CHAR = "#%$";
public static String generateSign(Map<String, Object> param) {
Set<String> keys = param.keySet();
//过滤掉sign,对key进行排序
List<String> sortedKeys = keys.stream().filter(key -> !Objects.equals(key, "sign")).sorted().collect(Collectors.toList());
//加上自定义字符串混淆算法
String calcSign = sortedKeys.stream().map(param::get).map(String::valueOf).collect(Collectors.joining(SEPERATE_CHAR));
//对字符串进行hash
calcSign = DigestUtils.sha1Hex(calcSign);
return calcSign;
}
将key进行排序,排序完获取value,然后它们之间使用特定分隔符分开来,让别人猜不到我们的加密算法。
最后的sign
sb = ParameterUtil.generateSign(ParameterUtil.getParameter(map, time));
System.out.println("加密混淆之后的字符串:" + sb);
//Todo 去数据库查询appId对应的Sercert,比如这里固定查出来是dajitui
sb = sb + "dajitui";
System.out.println("sign:" + SecureUtil.md5(sb));
特有的根据appid获取sercert过程,然后加入再进行md5加密。
使用aop+自定义注解
定义一个注解
@Target({METHOD, FIELD, TYPE})
@Retention(RUNTIME)
public @interface NoParameter {
}
一把梭哈
@NoParameter
@PostMapping("/rpc/test1")
public String a1(@RequestBody Student1 student1){
System.out.println("list:"+student1);
return "123";
}
切面逻辑
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class TestAspect {
@Pointcut("@annotation(com.example.demo.NoParameter)")
public void annotationPoinCut() {
}
@Before(value = "annotationPoinCut()")
public void beforeTest(JoinPoint point) throws IllegalAccessException {
String args = JSON.toJSONString(point.getArgs());
String sb = ParameterUtil.generateSign(ParameterUtil.postParameter(args, MyBetterInterceptor.local.get()));
sb = sb + "dajitui";
System.out.println("sign:" + SecureUtil.md5(sb));
if (!SecureUtil.md5(sb).equals(MyBetterInterceptor.localSign.get())) {
throw new IllegalAccessException("验签失败");
}
MyBetterInterceptor.local.remove();
MyBetterInterceptor.localSign.remove();
}
}