MrShi
5 天以前 98a1749e3e614da9ce8afbf3af7c474cd0bf6702
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
package com.doumee.device;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
 
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.*;
 
@RestController
@RequestMapping("/electronic")
public class ElectronicNotifyController {
 
    @RequestMapping("/notify")
    public String notify(String response_content, String timestamp, String sign) {
        System.out.println("timestamp: " + timestamp);
        System.out.println("response_content: " + response_content);
        System.out.println("sign: " + sign);
        // 验签
        if(!checkSign(response_content, timestamp, sign)) {
            System.out.println("sign check failed");
            return "sign check failed";
        }
        System.out.println("sign check success");
        List<Map<String, Object>> responseContent= new ArrayList<>();
        JSONArray contentArray = JSON.parseArray(response_content);
        for(int i = 0; i < contentArray.size(); ++i) {
            HashMap<String, Object> contentMap = new HashMap<>();
            JSONObject contentObject = contentArray.getJSONObject(i);
            Set<String> keySet = contentObject.keySet();
            for(String key: keySet) {
                contentMap.put(key, contentObject.getObject(key, Object.class));
            }
            responseContent.add(contentMap);
        }
        System.out.println("接收异步通知数据:" + responseContent);
        return "SUCCESS";
    }
 
    private boolean checkSign(String response_content, String timestamp, String sign) {
        // 随机字符串 后台获取
        String nonce = "XOfX547SeCIlhufeeBBwgZIN";
        String buf = response_content + timestamp + nonce;
        String encode = getMD5(buf);
        return encode.equals(sign);
    }
    // md5加密
    private String getMD5(String password) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        byte[] byteArray = password.getBytes(StandardCharsets.UTF_8);
 
        byte[] md5Bytes = md5.digest(byteArray);
        StringBuilder hexValue = new StringBuilder();
        for (byte md5Byte : md5Bytes) {
            int val = ((int) md5Byte) & 0xff;
            if (val < 16) {
                hexValue.append("0");
            }
 
            hexValue.append(Integer.toHexString(val));
        }
        return hexValue.toString();
    }
}