admin
2020-05-19 744594ef1a2f530fc3e86ea9dc48b62247f79420
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
package com.yeshi.fanli.aspect;
 
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
 
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.yeshi.utils.JsonUtil;
 
import com.yeshi.fanli.entity.accept.AcceptData;
import com.yeshi.fanli.log.LogHelper;
import com.yeshi.fanli.util.Constant;
import com.yeshi.fanli.util.StringUtil;
import com.yeshi.fanli.util.ThreadUtil;
 
import net.sf.json.JSONObject;
 
//客户端接口签名验证
@Component
@Aspect
@Order(2)
public class SignValidateAspect {
    public static final String EDP = "execution(* com.yeshi.fanli.controller.client.*.*.*(..))";
 
    public static String KEY = "";
 
    static {
        KEY = Constant.systemCommonConfig.getSignKey();
    }
 
    @Around(EDP)
    public Object testAround(ProceedingJoinPoint joinPoint) throws Throwable {
        Object[] args = joinPoint.getArgs();
        PrintWriter out = null;
        ServletRequestAttributes servletContainer = (ServletRequestAttributes) RequestContextHolder
                .getRequestAttributes();
 
        out = servletContainer.getResponse().getWriter();
        HttpServletRequest request = servletContainer.getRequest();
 
        AcceptData acceptData = null;
        for (Object obj : args) {
            if (obj instanceof AcceptData) {
                acceptData = (AcceptData) obj;
            } else if (obj instanceof HttpServletRequest) {
                request = (HttpServletRequest) obj;
            }
        }
        boolean isRight = true;
        if (acceptData == null) {
            out.print(JsonUtil.loadFalseResult(-1, "签名错误"));
            return null;
        }
 
        isRight = false;
 
        if ((acceptData.getPlatform() != null && acceptData.getPlatform().equalsIgnoreCase("android")
                && acceptData.getVersion() != null && Integer.parseInt(acceptData.getVersion()) > 21)
                || (acceptData.getPlatform() != null && acceptData.getPlatform().equalsIgnoreCase("ios")
                        && acceptData.getVersion() != null && Integer.parseInt(acceptData.getVersion()) > 24)) {
            isRight = signIsRight(request);
        } else if (acceptData.getPackages().startsWith("com.haicaojie")) {
            isRight = signIsRight(request);
        } else {
            isRight = signIsRight(acceptData);
        }
        // if (Integer.parseInt(acceptData.getVersion()) > 21) {
        // isRight = signIsRight(request);
        // } else {
        // isRight = signIsRight(acceptData);
        // }
 
        // 签名是否正确
        if (isRight) {
            // 判断签名超时
            if (Math.abs((Long.parseLong(acceptData.getTime()) - System.currentTimeMillis())) > 1000 * 60 * 10) {
                JSONObject data = new JSONObject();
                data.put("code", -2);
                data.put("msg", "时间错误");
                out.print(data);
                out.close();
                return null;
            }
 
            final String url = request.getRequestURI();
            @SuppressWarnings("unchecked")
            final Map<String, Object> params = request.getParameterMap();
            ThreadUtil.run(new Runnable() {
                @Override
                public void run() {
                    // 记录请求日志
                    LogHelper.requestInfo(url, params);
                }
            });
 
            Object obj = null;
            try {
                long startTime = System.currentTimeMillis();
                obj = joinPoint.proceed(args);
                final long responseTime = System.currentTimeMillis() - startTime;
                // 记录大于2s的请求
                if (responseTime >= 2000) {
                    ThreadUtil.run(new Runnable() {
 
                        @Override
                        public void run() {
                            LogHelper.requestTime(url, params, responseTime);
                        }
                    });
 
                }
 
            } catch (Throwable e) {
                LogHelper.errorDetailInfo(e, getHttpServletParams(request), request.getRequestURI().toString());
                if (!Constant.IS_TEST)
                    out.print(JsonUtil.loadFalseResult(90009, "服务器内部错误"));
                else
                    throw e;
            }
            return obj;
        } else {
            JSONObject data = new JSONObject();
            data.put("code", -1);
            data.put("msg", "签名错误");
            out.print(data);
            out.close();
            LogHelper.error("签名错误:" + request.getRequestURI() + "-" + getHttpServletParams(request));
            return null;
        }
    }
 
    private String getHttpServletParams(HttpServletRequest request) {
        if (request == null) {
            return "";
        }
        Map map = request.getParameterMap();
        if (map != null) {
            Iterator<String> its = map.keySet().iterator();
            JSONObject json = new JSONObject();
            while (its.hasNext()) {
                String next = its.next();
                if (map.get(next) != null) {
                    Object[] objects = (Object[]) map.get(next);
                    if (objects != null && objects.length > 0) {
                        json.put(next, objects[0].toString());
                    }
                }
            }
            return json.toString();
        }
        return "";
    }
 
    private boolean signIsRight(AcceptData acceptData) {
        String[] arr = new String[] { acceptData.getApiversion(), acceptData.getAppkey(), acceptData.getDevice(),
                acceptData.getPackages(), acceptData.getPlatform(), acceptData.getTime(), acceptData.getVersion() };
        Arrays.sort(arr);
        StringBuffer sb = new StringBuffer();
        for (String val : arr) {
            sb.append(val);
        }
        String md5 = StringUtil.Md5(sb.toString() + KEY);
        if (!md5.equals(acceptData.getSign())) {
            return false;
        } else {
            return true;
        }
    }
 
    /**
     * 判断签名的正确性 Android version>50
     * 
     * @param request
     * @return
     */
    @SuppressWarnings("unchecked")
    private boolean signIsRight(HttpServletRequest request) {
        Map<String, Object> map = request.getParameterMap();
        Iterator<String> its = map.keySet().iterator();
        List<String> list = new ArrayList<>();
        boolean fromWEB = false;
 
        while (its.hasNext()) {
            String key = its.next();
 
            // if (key.equalsIgnoreCase("callback")) {
            // fromWEB = true;
            // }
 
            if (key.equalsIgnoreCase("sign") || key.equalsIgnoreCase("callback") || key.equalsIgnoreCase("_")) {
                continue;
            }
            Object value = map.get(key);
            Object[] values = (Object[]) value;
            list.add(key + "=" + values[0].toString());
        }
        Collections.sort(list);
        String str = "";
        for (String st : list) {
            str += st + "&";
        }
        String sign = null;
        if (!fromWEB)
            sign = StringUtil.Md5(str + KEY);
        else
            sign = StringUtil.Md5(str + Constant.WEBPAGE_SIGN_KEY);
        if (sign.equalsIgnoreCase(request.getParameter("sign") + "")) {
            return true;
        } else {
            return false;
        }
    }
 
    public static boolean signIsRight(JSONObject json) {
        List<String> list = new ArrayList<>();
        for (Iterator<String> its = json.keySet().iterator(); its.hasNext();) {
            String key = its.next();
            if (!key.equalsIgnoreCase("sign"))
                list.add(key + "=" + json.optString(key));
        }
        Collections.sort(list);
        String str = "";
        for (String st : list) {
            str += st + "&";
        }
        String sign = StringUtil.Md5(str + KEY);
        if (sign.equalsIgnoreCase(json.optString("sign"))) {
            return true;
        } else {
            return false;
        }
 
    }
 
}