吉安感知网项目-后端
xiebin
2026-01-06 d207a86cdf1ab52ef8cb7cd83bad8fceab8038cf
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
package org.sxkj.common.utils;
 
import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.asymmetric.SM2;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
 
import org.sxkj.common.utils.sm3.SM2SignUtil;
 
 
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
 
 
 
public class AuthUtil {
    private static final ObjectMapper objectMapper = new ObjectMapper();
    /**
     * 国土调查云获取token
     * 1、获取当前时间的时间的毫秒时间戳A
     * 2、用调用方的数字证书B和A进行字符串顺序拼接得到字符串C
     * 3、获取字符串C的UTF-8字节数组D
     * 4、采用调用方的私钥,使用SM2签名算法对字节数组D进行签名得到字节数组E
     * 5、对字节数组E进行base64编码得到字符串F
     * 6、组装得到token:{B}.{A}.{F}
     * @return
     */
    public static String getToken() {
        String privateKey = "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3";
        String publicKey = "04225AACF606D800EA3C2C31FCF8FB161B15F7A8D0460DEB91013D4F228C455E76A2ED8D71BC6525B5DC5CC015C155479D8839950344AEE438A3A6305C90F8269F";
        SM2 sm2 = new SM2(privateKey, publicKey);
        sm2.usePlainEncoding();
        //SM2 token生成
        String certCode = "UAV32_WHR4E3UAJZTE3KE5IZFDGL7CBU";
        long timestamp = System.currentTimeMillis();
        //拼接待签名数据
        String needSignData = certCode + timestamp;
        byte[] needSignDataByte = needSignData.getBytes(StandardCharsets.UTF_8);
        //签名
        byte[] signData = sm2.sign(needSignDataByte);
//        String signDataHex = HexUtil.encodeHexStr(signData);
//        System.out.println("sign Hex:" + signDataHex);
        String signDataBase64 = Base64.encode(signData);
//        System.out.println("sign Base64:" + signDataBase64);
        //生成token
//        String token = certCode + "." + timestamp + "." + signDataBase64;
//        System.out.println("token:" + token);
        //SM2 token验证
//        boolean rst1 = sm2.verify(needSignDataByte, signData);
//        System.out.println("verify result:" + rst1);
//        boolean rst2 = sm2.verify(needSignDataByte, HexUtil.decodeHex(signDataHex));
//        System.out.println("verify result:" + rst2);
//        boolean rst3 = sm2.verify(needSignDataByte, Base64.decode(signDataBase64));
//        System.out.println("verify result:" + rst3);
        return certCode + "." + timestamp + "." + signDataBase64;
 
    }
 
    public static boolean tokenVerify(String token) {
 
        String [] tokenStrs = token.split("\\.");
        if (tokenStrs.length < 3) {
            return false;
        }
 
        String privateKey = "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3";
        String publicKey = "04225AACF606D800EA3C2C31FCF8FB161B15F7A8D0460DEB91013D4F228C455E76A2ED8D71BC6525B5DC5CC015C155479D8839950344AEE438A3A6305C90F8269F";
        SM2 sm2 = new SM2(privateKey, publicKey);
        sm2.usePlainEncoding();
 
        //拼接待签名数据
        String needSignData = tokenStrs[0] + tokenStrs[1];
        byte[] needSignDataByte = needSignData.getBytes(StandardCharsets.UTF_8);
 
        return sm2.verify(needSignDataByte, Base64.decode(tokenStrs[2]));
    }
 
    public static boolean tokenVerify2(String token,String publicKey) {
        String [] tokenStrs = token.split("\\.");
        if (tokenStrs.length < 3) {
            return false;
        }
 
        String privateKey = "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3";
//        String publicKey ="047719B34C1149EE1068A18E207E2BA4D0F61C42D2336FD0E0AE76D75AD556AB50DF8B8A395624F589DD3FBE12FB1E0DEA059114BD15D0629AE3408FDBC48212FA" ;
        SM2 sm2 = new SM2(privateKey, publicKey);
        sm2.usePlainEncoding();
 
        //拼接待签名数据
        String needSignData = tokenStrs[0] + tokenStrs[1];
        byte[] needSignDataByte = needSignData.getBytes(StandardCharsets.UTF_8);
 
        return sm2.verify(needSignDataByte, Base64.decode(tokenStrs[2]));
    }
 
 
    public static String getPublicKey() {
        String urlString = "https://xcx.geoway.com.cn:8033/v1/cert/getPublicKey";
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("x-lc-token", "UAV32_WHR4E3UAJZTE3KE5IZFDGL7CBU.1724764016746.mDm0ylBxqPyhX2wEishoTh3EulqMRxji4yLGscnew4ZGVfiV9qqJHTzTIbvbLtXOrog6YOHqFTYNy+j06yQ3IA=="); // 设置token
 
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String secret = connection.getHeaderField("x-lc-secret");
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
 
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
 
                // 解析响应中的 JSON 并提取 data 信息
                JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                String data = jsonResponse.getString("data");
                byte[] bytes= SM2SignUtil.deSM2(secret, "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
                return SM4Util.decrypt(bytes,data);
            } else {
                System.out.println("GET 请求失败。响应码:" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static Map<String,String> getPubulicKeys(String token) {
        String urlString = "https://xcx.geoway.com.cn:8033/v1/cert/getcertbycertcode?certcode="+splitBeforeFirstDot(token);
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("x-lc-token",  getToken()); // 设置token
 
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String secret = connection.getHeaderField("x-lc-secret");
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
 
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
 
                // 解析响应中的 JSON 并提取 data 信息
                JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                String data = jsonResponse.getString("data");
                byte[] bytes= SM2SignUtil.deSM2(secret, "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
                // 解析JSON字符串
                JSONObject jsonObject = JSONObject.parseObject(SM4Util.decrypt(bytes,data));
 
                // 获取publickey字段的值
 
                Map<String,String> map =new HashMap<>();
                map.put("publickey",jsonObject.getString("publickey"));
                map.put("orgname",jsonObject.getString("orgname"));
                return map;
            } else {
                System.out.println("GET 请求失败。响应码:" + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String splitBeforeFirstDot(String input) {
        if (input == null || input.isEmpty()) {
            return input;
        }
        return input.split("\\.")[0];
    }
    public static String getPubulicKey(String token) {
        String urlString = "https://xcx.geoway.com.cn:8033/v1/cert/getcertbycertcode?certcode="+splitBeforeFirstDot(token);
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("x-lc-token",  getToken()); // 设置token
 
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                String secret = connection.getHeaderField("x-lc-secret");
                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String inputLine;
                StringBuilder response = new StringBuilder();
 
                while ((inputLine = in.readLine()) != null) {
                    response.append(inputLine);
                }
                in.close();
 
                // 解析响应中的 JSON 并提取 data 信息
                JSONObject jsonResponse = JSONObject.parseObject(response.toString());
                String data = jsonResponse.getString("data");
                byte[] bytes= SM2SignUtil.deSM2(secret, "00D631FD5615416EAB63D33A9E66E801F95DE840567504210080006081DE877AE3");
                // 解析JSON字符串
                JSONObject jsonObject = JSONObject.parseObject(SM4Util.decrypt(bytes,data));
 
                // 获取publickey字段的值
 
                return jsonObject.getString("publickey");
            } else {
                System.out.println("GET 请求失败。响应码:" + responseCode);
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public static <T> String buildRequestBody(T obj) {
        try {
            return objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            throw new RuntimeException("对象转换为JSON字符串时发生错误", e);
        }
    }
 
 
}