Преглед на файлове

Merge branch 'bgy' of SH-Arbitrate/Arbitrate-Backend into dev

bgy преди 2 години
родител
ревизия
061afe4cf4

+ 30
- 0
ruoyi-admin/src/main/java/com/ruoyi/web/controller/bestsign/RegisterController.java Целия файл

@@ -0,0 +1,30 @@
1
+package com.ruoyi.web.controller.bestsign;
2
+
3
+import com.ruoyi.bestsign.domain.PersonRegisterVO;
4
+import com.ruoyi.bestsign.service.SignRegisterService;
5
+import com.ruoyi.common.core.domain.AjaxResult;
6
+import com.ruoyi.wisdomarbitrate.domain.CaseApplication;
7
+import org.springframework.beans.factory.annotation.Autowired;
8
+import org.springframework.validation.annotation.Validated;
9
+import org.springframework.web.bind.annotation.PostMapping;
10
+import org.springframework.web.bind.annotation.RequestBody;
11
+import org.springframework.web.bind.annotation.RequestMapping;
12
+import org.springframework.web.bind.annotation.RestController;
13
+
14
+@RestController
15
+@RequestMapping("/register")
16
+public class RegisterController {
17
+    @Autowired
18
+    SignRegisterService signRegisterService;
19
+
20
+    /**
21
+     * 注册上上签个人用户
22
+     *
23
+     * @param personRegisterVO
24
+     * @return
25
+     */
26
+    @PostMapping("/registerPerson")
27
+    public AjaxResult createDocument(@Validated @RequestBody PersonRegisterVO personRegisterVO) {
28
+        return signRegisterService.registerPerson(personRegisterVO);
29
+    }
30
+}

+ 5
- 0
ruoyi-admin/src/main/resources/application.yml Целия файл

@@ -102,6 +102,11 @@ spring:
102 102
         smtp:
103 103
           socketFactoryClass: javax.net.ssl.SSLSocketFactory
104 104
         debug: false
105
+#上上签配置参数
106
+ssq:
107
+  developerId: 1695872832013855470
108
+  privateKey: MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCiDRuz+dxqkWqHdov0hK+KEWLw/e8MQSqkZZ4c01Yr6cSmQiWyV8Xin0u5S/EA02FWxpjLi1nLriVtOBhZGsoryFmcJrwzSnQ5PORP/HhfcAWFE/Y+3qSQS1OiU7e5wbReCgEUvx4GHZuhdu8cOvq5DG9l33YFZrIEMBTmnf8eKT54STx0tjcKl7U6B6nsiThy3zVtpWXVv6H1HGmxC0KT4EQ388s/PFjrwmk+GFb3EpKCns/GQHf7QrtNz1ZOgCXfgQiQ+91/tcngzUH+zMCIxn5lS+ENAxVI6Ev3W9Y0QHtKwmO4ORVuAskJYzBB2xKI/gw8+PUXNziMAKXuoUAjAgMBAAECggEAd7yHw6vTGUrpE76cGsgPjEzcdoSqpLth7qbG9TWSblAEZXRqtiP0q0ZYhUl/gcSuH5gOPhdw+fZq4RCZrP0GdONMkvxsAtn4lnJPoGpD5wC2k2X0hO+tWJDP8xk4n6BozTNHKTUt0gb+f4eJlapep2xwwy0h30vKLR3504zafEV9j/2D8l5TFSv6rd3UVxUvrDKQ9mhfATEUlrTpjs0SfWupMkr4j7TuJJ8qSUSiEADe4hyUB6+LouDZCt8jV4aLojQBJKrQ6VPVdDFkHGsePu4tHtvcKsaOZJ0pjpJ7MT6D5ElD/sJjo0g/3qK5/FToVFVbrxtykVreK6mE5oSTQQKBgQDpEFSgH1d4N7NsZhviaCIUkB97hO0jpRbD7UZirzZ9ok96Fk+SmfhdmypDMoiaRHCNhQuu5dI9mg5RbUhz9mCZnAhzJRL+DmE4bhNvQmbtJA7KT6n/AdH2zy0mYulrcG17dQspvTr/5421PTEE2+FRoCbG6hBsSSUit9HLvAU13QKBgQCx/7ql+hbx+t0Yb02XckBHiA+MWrFLO4dMX9cKf3LldC0nhn0K9HOSoZmM0KcmXRnMo+/4t89xOJRl7JRXwcLoy/64OaUBVv+8FFV1yY4THka3nEnQE40vVWy+vuNJtt+eKlEhJ35N1GIHXo7/4j0POtEuNU7KSqMnLUD+Oy/t/wKBgEiajcJUASuyLnLWXFlrlzJQs34HKtiv1Se0Avk7G/6HUbr2uFMzI+wFKmVEmMl2CJoNmFYjwhruowc6xBdb6TvxH7C/G+uJD0BFCkjeprG5SeI8bvjB2GbKo4YRyiVuIK0VCSU3jemqeLq9FUguN0L2YR4WTIdvQeJO4UxWhkkBAoGBAJk7TxDHZK1XirIYTzGK928c4FWxVWMwkd7buqGc6epBwwV9r3OY0U1vtGIW1W4fQ7B5iIISqpALZyT/Lw0FDqedxWAOr8+hd3IQBynpI1et/q7d6mUoD6ip332tkrjIp2TfhQwHlaGmreUuL+h0eJ/9wEoJNhTLf/yf5o11omM9AoGBAOLVlXR9FbU2Ubpp3HwTumSzKDWzq3T5eQcqC1zE3BPOo29uAf9BQTumPxe51U64egttW/nif5FH4v4Gentmxb2B2ckdOs/u9zIWz3JPfHU7RqMyMokuWrQ6lMoiSYpH3MSHoavLyAEhAnpceX3oktXgpYHO9d8MfON3XKJl23ip
109
+  serverHost: http://openapi.bestsign.info/openapi/v2/
105 110
 
106 111
 # token配置
107 112
 token:

+ 22
- 0
ruoyi-system/src/main/java/com/ruoyi/bestsign/domain/CredentialVO.java Целия файл

@@ -0,0 +1,22 @@
1
+package com.ruoyi.bestsign.domain;
2
+
3
+import lombok.AllArgsConstructor;
4
+import lombok.Builder;
5
+import lombok.Data;
6
+import lombok.NoArgsConstructor;
7
+
8
+@Data
9
+@NoArgsConstructor
10
+@AllArgsConstructor
11
+@Builder
12
+public class CredentialVO {
13
+    /**
14
+     * 用户证件号
15
+     */
16
+    private String identity;
17
+    /**
18
+     * 用户证件类型
19
+     * 默认用“0”, "0"表示身份证,会校验18位身份证号格式。0-居民身份证; 1-护照;6-社会保障卡; B-港澳居民往来内地通行证; C-台湾居民来往大陆通行证; E-户口簿; F-临时居民身份证;P-外国人永久居留证;Z-其他证件
20
+     */
21
+    private String identityType;
22
+}

+ 29
- 0
ruoyi-system/src/main/java/com/ruoyi/bestsign/domain/PersonRegisterVO.java Целия файл

@@ -0,0 +1,29 @@
1
+package com.ruoyi.bestsign.domain;
2
+
3
+import lombok.AllArgsConstructor;
4
+import lombok.Builder;
5
+import lombok.Data;
6
+import lombok.NoArgsConstructor;
7
+
8
+@Data
9
+@NoArgsConstructor
10
+@AllArgsConstructor
11
+@Builder
12
+public class PersonRegisterVO {
13
+    /**
14
+     * 用户帐号
15
+     * 用户名称
16
+     * 用户类型
17
+     * 用户邮箱
18
+     * 用户手机号
19
+     * 用户证件信息对象
20
+     * 是否申请证书
21
+     */
22
+    private String account;
23
+    private String name;
24
+    private String userType;
25
+    private String mail;
26
+    private String mobile;
27
+    private CredentialVO credential;
28
+    private String applyCert;
29
+}

+ 14
- 0
ruoyi-system/src/main/java/com/ruoyi/bestsign/service/SignRegisterService.java Целия файл

@@ -0,0 +1,14 @@
1
+package com.ruoyi.bestsign.service;
2
+
3
+import com.ruoyi.bestsign.domain.PersonRegisterVO;
4
+import com.ruoyi.common.core.domain.AjaxResult;
5
+
6
+public interface SignRegisterService {
7
+    /**
8
+     * 注册上上签个人用户
9
+     *
10
+     * @param personRegisterVO
11
+     * @return
12
+     */
13
+    AjaxResult registerPerson(PersonRegisterVO personRegisterVO);
14
+}

+ 39
- 0
ruoyi-system/src/main/java/com/ruoyi/bestsign/service/impl/RegisterServiceImpl.java Целия файл

@@ -0,0 +1,39 @@
1
+package com.ruoyi.bestsign.service.impl;
2
+
3
+
4
+import com.ruoyi.bestsign.domain.PersonRegisterVO;
5
+import com.ruoyi.bestsign.service.SignRegisterService;
6
+import com.ruoyi.bestsign.utils.BestsignOpenApiClient;
7
+import com.ruoyi.common.core.domain.AjaxResult;
8
+import org.springframework.beans.factory.annotation.Autowired;
9
+import org.springframework.stereotype.Service;
10
+
11
+@Service
12
+public class RegisterServiceImpl implements SignRegisterService {
13
+    @Autowired
14
+    BestsignOpenApiClient bestsignOpenApiClient;
15
+
16
+    /**
17
+     * 注册上上签个人用户
18
+     *
19
+     * @param personRegisterVO
20
+     * @return
21
+     */
22
+    @Override
23
+    public AjaxResult registerPerson(PersonRegisterVO personRegisterVO) {
24
+        try {
25
+            String s = bestsignOpenApiClient.userPersonalReg(personRegisterVO.getAccount(),
26
+                    personRegisterVO.getName(),
27
+                    personRegisterVO.getMail(),
28
+                    personRegisterVO.getMobile(),
29
+                    personRegisterVO.getCredential().getIdentity(),
30
+                    personRegisterVO.getCredential().getIdentityType(),
31
+                    null, null, null, null, null);
32
+            AjaxResult.success(s);
33
+        } catch (Exception e) {
34
+            e.printStackTrace();
35
+            return AjaxResult.error(e.getMessage());
36
+        }
37
+        return AjaxResult.success();
38
+    }
39
+}

+ 148
- 0
ruoyi-system/src/main/java/com/ruoyi/bestsign/utils/BestsignOpenApiClient.java Целия файл

@@ -0,0 +1,148 @@
1
+package com.ruoyi.bestsign.utils;
2
+
3
+import com.alibaba.fastjson.JSON;
4
+import com.alibaba.fastjson.JSONObject;
5
+import lombok.Data;
6
+import lombok.extern.slf4j.Slf4j;
7
+import org.springframework.beans.factory.annotation.Value;
8
+import org.springframework.stereotype.Component;
9
+
10
+import java.io.IOException;
11
+
12
+/**
13
+ * 上上签混合云SDK客户端
14
+ */
15
+@Component
16
+@Data
17
+@Slf4j
18
+public class BestsignOpenApiClient {
19
+    /**
20
+     * 开发者id
21
+     */
22
+    @Value("${ssq.developerId}")
23
+    private String developerId;
24
+    /**
25
+     * 开发者私钥
26
+     */
27
+    @Value("${ssq.privateKey}")
28
+    private String privateKey;
29
+    /**
30
+     * Host地址
31
+     */
32
+    @Value("${ssq.serverHost}")
33
+    private String serverHost;
34
+    private static String urlSignParams = "?developerId=%s&rtick=%s&signType=rsa&sign=%s";
35
+
36
+//	public BestsignOpenApiClient(String developerId, String privateKey,
37
+//                                 String serverHost) {
38
+//		this.developerId = developerIds;
39
+//		this.privateKey = privateKey;
40
+//		this.serverHost = serverHost;
41
+//	}
42
+
43
+    /**
44
+     * POST方法示例
45
+     * 个人用户注册
46
+     *
47
+     * @param account       用户账号
48
+     * @param name          姓名
49
+     * @param mail          用来接收通知邮件的电子邮箱
50
+     * @param mobile        用来接收通知短信的手机号码
51
+     * @param identity      证件号码
52
+     * @param identityType  枚举值:0-身份证,目前仅支持身份证
53
+     * @param contactMail   电子邮箱
54
+     * @param contactMobile 手机号码
55
+     * @param province      省份
56
+     * @param city          城市
57
+     * @param address       地址
58
+     * @return 异步申请任务单号
59
+     * @throws IOException
60
+     */
61
+    public String userPersonalReg(String account, String name, String mail,
62
+                                  String mobile, String identity, String identityType,
63
+                                  String contactMail, String contactMobile, String province,
64
+                                  String city, String address) throws Exception {
65
+        String host = this.serverHost;
66
+        String method = "/user/reg/";
67
+
68
+        // 组装请求参数,作为requestbody
69
+        JSONObject requestBody = new JSONObject();
70
+        requestBody.put("account", account);
71
+        requestBody.put("name", name);
72
+        requestBody.put("userType", "1");
73
+        requestBody.put("mail", mail);
74
+        requestBody.put("mobile", mobile);
75
+
76
+        JSONObject credential = new JSONObject();
77
+        credential.put("identity", identity);
78
+        credential.put("identityType", identityType);
79
+        credential.put("contactMail", contactMail);
80
+        credential.put("contactMobile", contactMobile);
81
+        credential.put("province", province);
82
+        credential.put("city", city);
83
+        credential.put("address", address);
84
+        requestBody.put("credential", credential);
85
+        //是否申请证书
86
+        requestBody.put("applyCert", "2");
87
+        // 生成一个时间戳参数
88
+        String rtick = RSAUtils.getRtick();
89
+        // 计算参数签名
90
+        String paramsSign = RSAUtils.calcRsaSign(this.developerId,
91
+                this.privateKey, this.serverHost, method, rtick, null,
92
+                requestBody.toJSONString());
93
+        // 签名参数追加为url参数
94
+        String fullUrlParams = String.format(urlSignParams, this.developerId,
95
+                rtick, paramsSign);
96
+
97
+        // 发送POST请求
98
+        String responseBody = HttpClientSender.sendHttpPost(this.serverHost, method,
99
+                fullUrlParams, requestBody.toJSONString());
100
+        System.out.println(responseBody);
101
+        // 返回结果解析
102
+        JSONObject userObj = JSON.parseObject(responseBody);
103
+        // 返回errno为0,表示成功,其他表示失败
104
+        if (userObj.getIntValue("errno") == 0) {
105
+            JSONObject data = userObj.getJSONObject("data");
106
+            if (data != null) {
107
+                //对返回data进行处理
108
+                String taskId = data.getString("taskId");
109
+                return taskId;
110
+            }
111
+        } else {
112
+            //接口返回异常
113
+            System.out.println(userObj.getIntValue("errno"));
114
+            System.out.println(userObj.getString("errmsg"));
115
+        }
116
+        return userObj.toJSONString();
117
+    }
118
+
119
+    /**
120
+     * GET方法示例
121
+     * 下载合同PDF文件
122
+     *
123
+     * @param contractId 合同编号
124
+     * @return
125
+     * @throws Exception
126
+     */
127
+    public byte[] contractDownload(String contractId) throws Exception {
128
+        String host = this.serverHost;
129
+        String method = "/storage/contract/download/";
130
+
131
+        // 组装url参数
132
+        String urlParams = "contractId=" + contractId;
133
+
134
+        // 生成一个时间戳参数
135
+        String rtick = RSAUtils.getRtick();
136
+        // 计算参数签名
137
+        String paramsSign = RSAUtils.calcRsaSign(this.developerId,
138
+                this.privateKey, host, method, rtick, urlParams, null);
139
+        // 签名参数追加为url参数
140
+        urlParams = String.format(urlSignParams, this.developerId, rtick,
141
+                paramsSign) + "&" + urlParams;
142
+        // 发送请求
143
+        byte[] responseBody = HttpClientSender.sendHttpGet(host, method,
144
+                urlParams);
145
+        // 返回结果解析
146
+        return responseBody;
147
+    }
148
+}

+ 390
- 0
ruoyi-system/src/main/java/com/ruoyi/bestsign/utils/HttpClientSender.java Целия файл

@@ -0,0 +1,390 @@
1
+package com.ruoyi.bestsign.utils;
2
+
3
+import org.apache.http.HttpEntity;
4
+import org.apache.http.client.config.RequestConfig;
5
+import org.apache.http.client.methods.CloseableHttpResponse;
6
+import org.apache.http.client.methods.HttpGet;
7
+import org.apache.http.client.methods.HttpPost;
8
+import org.apache.http.config.Registry;
9
+import org.apache.http.config.RegistryBuilder;
10
+import org.apache.http.conn.socket.ConnectionSocketFactory;
11
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
12
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
13
+import org.apache.http.entity.StringEntity;
14
+import org.apache.http.impl.client.CloseableHttpClient;
15
+import org.apache.http.impl.client.HttpClients;
16
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
17
+import org.apache.http.util.EntityUtils;
18
+
19
+import javax.net.ssl.SSLContext;
20
+import javax.net.ssl.TrustManager;
21
+import javax.net.ssl.X509TrustManager;
22
+import java.io.IOException;
23
+import java.io.InputStream;
24
+import java.io.UnsupportedEncodingException;
25
+import java.net.MalformedURLException;
26
+import java.net.URL;
27
+import java.net.URLEncoder;
28
+import java.security.cert.CertificateException;
29
+import java.security.cert.X509Certificate;
30
+import java.util.HashMap;
31
+import java.util.Map;
32
+
33
+public class HttpClientSender {
34
+
35
+    private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = null;
36
+    private static Map<String, CloseableHttpClient> httpClients = new HashMap<String, CloseableHttpClient>();
37
+
38
+    private static Object o = new Object();
39
+
40
+    public static String sendHttpPost(String host, String method, String urlParams, String sendData) throws IOException {
41
+
42
+        String requestUrl = host + method + urlParams;
43
+
44
+        Map<String, Object> response = request("POST", requestUrl, sendData, null);
45
+        int responseCode = Integer.parseInt(response.get("responseCode").toString());
46
+        byte[] responseBytes = (byte[]) response.get("responseData");
47
+        String responseString;
48
+        try {
49
+            responseString = new String(responseBytes, "UTF-8");
50
+        } catch (UnsupportedEncodingException e) {
51
+            responseString = new String(responseBytes);
52
+        }
53
+        //请求返回结果无论成功失败,http-status均为200
54
+        if (responseCode == 200) {
55
+            //返回结果
56
+            return responseString;
57
+        } else {
58
+            throw new IOException(responseCode + ":" + responseString);
59
+        }
60
+    }
61
+
62
+    public static byte[] sendHttpGet(String host, String method, String urlParams) throws IOException {
63
+        String requestUrl = host + method + urlParams;
64
+        Map<String, Object> response = request("GET", requestUrl, null, null);
65
+        int responseCode = Integer.parseInt(response.get("responseCode").toString());
66
+        byte[] responseBytes = (byte[]) response.get("responseData");
67
+        //请求返回结果无论成功失败,http-status均为200
68
+        if (responseCode == 200) {
69
+            //返回结果
70
+            return responseBytes;
71
+        } else {
72
+            throw new IOException(responseCode + "");
73
+        }
74
+    }
75
+
76
+    public static String urlencode(String data) {
77
+        return urlencode(data, "UTF-8");
78
+    }
79
+
80
+    public static String urlencode(String data, String charset) {
81
+        try {
82
+            return URLEncoder.encode(data, charset);
83
+        } catch (UnsupportedEncodingException e) {
84
+            throw new RuntimeException(e.getMessage(), e);
85
+        }
86
+    }
87
+
88
+    public static Map<String, Object> request(String method, String url, Object sendData, Map<String, String> headers) throws IOException {
89
+
90
+
91
+        String requestPath;
92
+        try {
93
+            requestPath = new URL(url).getPath();
94
+        } catch (MalformedURLException e) {
95
+            throw new RuntimeException(e.getMessage(), e);
96
+        }
97
+        CloseableHttpClient httpClient = getHttpClient(requestPath);
98
+
99
+        Map<String, Object> response = null;
100
+        if ("POST".equals(method)) {
101
+            response = sendPost(httpClient, url, headers, sendData);
102
+        } else {
103
+            response = sendGet(httpClient, url, headers);
104
+        }
105
+        return response;
106
+    }
107
+
108
+    private static Map<String, Object> sendPost(CloseableHttpClient httpClient, String url, Map<String, String> headers, Object sendData) throws IOException {
109
+        String tag = "[HttpRequester] [POST " + url + "]";
110
+        int responseCode = -1;
111
+        byte[] responseBytes = null;
112
+
113
+        HttpPost request = new HttpPost(url);
114
+        if (headers != null && headers.size() > 0) {
115
+            for (String name : headers.keySet()) {
116
+                String value = headers.get(name);
117
+                request.setHeader(name, value);
118
+            }
119
+        }
120
+        if (sendData != null) {
121
+            StringEntity stringEntity = new StringEntity((String) sendData, "UTF-8");
122
+            stringEntity.setContentType("application/json");
123
+            request.setEntity(stringEntity);
124
+
125
+            HttpEntity httpEntity = null;
126
+            IOException exception = null;
127
+            for (int i = 0; i < 3; i++) {
128
+                try {
129
+                    CloseableHttpResponse response = httpClient.execute(request);
130
+                    responseCode = response.getStatusLine().getStatusCode();
131
+                    httpEntity = response.getEntity();
132
+
133
+                    String responseBody = EntityUtils.toString(httpEntity, "utf-8");
134
+                    if (responseBody != null) {
135
+                        responseBytes = responseBody.getBytes();
136
+                    } else {
137
+                        InputStream respStream = null;
138
+                        try {
139
+                            respStream = httpEntity.getContent();
140
+                            int respBodySize = respStream.available();
141
+                            if (respBodySize <= 0)
142
+                                throw new IOException("Invalid respBodySize: " + respBodySize);
143
+                            responseBytes = new byte[respBodySize];
144
+                            if (respStream.read(responseBytes) != respBodySize)
145
+                                throw new IOException("Read respBody Error");
146
+                        } catch (Exception e) {
147
+                        } finally {
148
+                            if (respStream != null) {
149
+                                respStream.close();
150
+                            }
151
+                        }
152
+                    }
153
+
154
+                    exception = null;
155
+                    break;
156
+                } catch (UnsupportedOperationException e) {
157
+                    try {
158
+                        EntityUtils.consume(httpEntity);
159
+                    } catch (IOException e2) {
160
+
161
+                    }
162
+                    throw new RuntimeException(e.getMessage(), e);
163
+                } catch (IOException e) {
164
+                    e.printStackTrace();
165
+                    exception = e;
166
+                    try {
167
+                        EntityUtils.consume(httpEntity);
168
+                    } catch (IOException e2) {
169
+
170
+                    }
171
+                    if (i < 2) {
172
+                        try {
173
+                            Thread.sleep(5);
174
+                        } catch (InterruptedException e2) {
175
+
176
+                        }
177
+                    }
178
+                }
179
+            }
180
+            if (exception != null) {
181
+                throw exception;
182
+            }
183
+
184
+        }
185
+        Map<String, Object> response = new HashMap<String, Object>();
186
+        response.put("responseCode", responseCode);
187
+        response.put("responseData", responseBytes);
188
+        String loggerResponseString = getLoggerString(responseBytes, 256);
189
+        return response;
190
+    }
191
+
192
+    private static Map<String, Object> sendGet(CloseableHttpClient httpClient, String url, Map<String, String> headers) throws IOException {
193
+        String tag = "[HttpRequester] [GET " + url + "]";
194
+        int responseCode = -1;
195
+        byte[] responseBytes = null;
196
+
197
+        HttpGet request = new HttpGet(url);
198
+        if (headers != null && headers.size() > 0) {
199
+            for (String name : headers.keySet()) {
200
+                String value = headers.get(name);
201
+                request.setHeader(name, value);
202
+            }
203
+        }
204
+        HttpEntity httpEntity = null;
205
+        IOException exception = null;
206
+        for (int i = 0; i < 3; i++) {
207
+            try {
208
+                CloseableHttpResponse response = httpClient.execute(request);
209
+                responseCode = response.getStatusLine().getStatusCode();
210
+                httpEntity = response.getEntity();
211
+
212
+                byte[] responseBody = EntityUtils.toByteArray(httpEntity);
213
+                if (responseBody != null) {
214
+                    responseBytes = responseBody;
215
+                } else {
216
+                    InputStream respStream = null;
217
+                    try {
218
+                        respStream = httpEntity.getContent();
219
+                        int respBodySize = respStream.available();
220
+                        if (respBodySize <= 0)
221
+                            throw new IOException("Invalid respBodySize: " + respBodySize);
222
+                        responseBytes = new byte[respBodySize];
223
+                        if (respStream.read(responseBytes) != respBodySize)
224
+                            throw new IOException("Read respBody Error");
225
+                    } catch (Exception e) {
226
+                    } finally {
227
+                        if (respStream != null) {
228
+                            respStream.close();
229
+                        }
230
+                    }
231
+                }
232
+
233
+                exception = null;
234
+                break;
235
+            } catch (UnsupportedOperationException e) {
236
+                try {
237
+                    EntityUtils.consume(httpEntity);
238
+                } catch (IOException e2) {
239
+
240
+                }
241
+                throw new RuntimeException(e.getMessage(), e);
242
+            } catch (IOException e) {
243
+                e.printStackTrace();
244
+                exception = e;
245
+                try {
246
+                    EntityUtils.consume(httpEntity);
247
+                } catch (IOException e2) {
248
+
249
+                }
250
+                if (i < 2) {
251
+                    try {
252
+                        Thread.sleep(5);
253
+                    } catch (InterruptedException e2) {
254
+
255
+                    }
256
+                }
257
+            }
258
+        }
259
+        if (exception != null) {
260
+            throw exception;
261
+        }
262
+        Map<String, Object> response = new HashMap<String, Object>();
263
+        response.put("responseCode", responseCode);
264
+        response.put("responseData", responseBytes);
265
+        String loggerResponseString = getLoggerString(responseBytes, 256);
266
+        System.out.println(tag + " response " + responseCode + " " + loggerResponseString);
267
+        return response;
268
+    }
269
+
270
+    private static String getLoggerString(final byte[] data, int maxLength) {
271
+        String loggerString;
272
+        if (data.length > maxLength) {
273
+            byte[] shortData = new byte[maxLength];
274
+            System.arraycopy(data, 0, shortData, 0, shortData.length);
275
+            try {
276
+                loggerString = new String(shortData, "UTF-8") + "...";
277
+            } catch (UnsupportedEncodingException e) {
278
+                loggerString = new String(shortData) + "...";
279
+            }
280
+        } else {
281
+            try {
282
+                loggerString = new String(data, "UTF-8");
283
+            } catch (UnsupportedEncodingException e) {
284
+                loggerString = new String(data);
285
+            }
286
+        }
287
+
288
+        char[] chars = new char[loggerString.length()];
289
+        loggerString.getChars(0, loggerString.length(), chars, 0);
290
+        for (int i = 0; i < chars.length; i++) {
291
+            char c = chars[i];
292
+            if (c == '\n' || c == '\r') {
293
+                chars[i] = ' ';
294
+            }
295
+        }
296
+        return new String(chars);
297
+    }
298
+
299
+    private static CloseableHttpClient getHttpClient(String requestPath) {
300
+        if (httpClients.containsKey(requestPath)) {
301
+            return httpClients.get(requestPath);
302
+        }
303
+        if (poolingHttpClientConnectionManager == null) {
304
+            synchronized (o) {
305
+                if (poolingHttpClientConnectionManager == null) {
306
+                    poolingHttpClientConnectionManager = HttpClientUtils.createHttpClientConnectionManager();
307
+                }
308
+            }
309
+        }
310
+        synchronized (httpClients) {
311
+            if (httpClients.containsKey(requestPath)) {
312
+                return httpClients.get(requestPath);
313
+            }
314
+            CloseableHttpClient httpClient = HttpClientUtils.createHttpClient(poolingHttpClientConnectionManager);
315
+            httpClients.put(requestPath, httpClient);
316
+            return httpClient;
317
+        }
318
+    }
319
+
320
+    private static class HttpClientUtils {
321
+
322
+        // 默认连接超时
323
+        private static int defaultConnectTimeout = 6000;
324
+        // 默认读取超时
325
+        private static int defaultReadTimeout = 30000;
326
+
327
+        public static CloseableHttpClient createHttpClient(PoolingHttpClientConnectionManager connManager) {
328
+            //HttpHost httpHost = new HttpHost("10.211.55.4", 8888);
329
+            CloseableHttpClient httpClient = HttpClients.custom()
330
+                    //.setProxy(httpHost)
331
+                    .setConnectionManager(connManager)
332
+                    .disableContentCompression()
333
+                    .setSSLContext(getSslcontext())
334
+                    .setDefaultRequestConfig(getRequestConfig())
335
+                    .build();
336
+            return httpClient;
337
+        }
338
+
339
+        public static PoolingHttpClientConnectionManager createHttpClientConnectionManager() {
340
+            SSLConnectionSocketFactory sslConnectionSocketFactory = null;
341
+            try {
342
+                sslConnectionSocketFactory = new SSLConnectionSocketFactory(getSslcontext(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
343
+            } catch (Exception e) {
344
+                throw new RuntimeException(e.getMessage(), e);
345
+            }
346
+            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
347
+                    .register("https", sslConnectionSocketFactory)
348
+                    .register("http", new PlainConnectionSocketFactory())
349
+                    .build();
350
+            PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
351
+            cm.setMaxTotal(500);
352
+            cm.setDefaultMaxPerRoute(500);
353
+            return cm;
354
+        }
355
+
356
+        private static RequestConfig getRequestConfig() {
357
+            RequestConfig defaultRequestConfig = RequestConfig.custom()
358
+                    .setConnectionRequestTimeout(defaultConnectTimeout)
359
+                    .setSocketTimeout(defaultReadTimeout)
360
+                    .build();
361
+            return defaultRequestConfig;
362
+        }
363
+
364
+        private static SSLContext getSslcontext() {
365
+            SSLContext sslContext = null;
366
+            try {
367
+                sslContext = SSLContext.getInstance("TLS");
368
+                TrustManager tm = new X509TrustManager() {
369
+                    @Override
370
+                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
371
+                    }
372
+
373
+                    @Override
374
+                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
375
+                    }
376
+
377
+                    @Override
378
+                    public X509Certificate[] getAcceptedIssuers() {
379
+                        return null;
380
+                    }
381
+                };
382
+                sslContext.init(null, new TrustManager[]{tm}, null);
383
+
384
+            } catch (Exception e) {
385
+                e.printStackTrace();
386
+            }
387
+            return sslContext;
388
+        }
389
+    }
390
+}

+ 281
- 0
ruoyi-system/src/main/java/com/ruoyi/bestsign/utils/RSAUtils.java Целия файл

@@ -0,0 +1,281 @@
1
+package com.ruoyi.bestsign.utils;
2
+
3
+import org.apache.commons.codec.binary.Base64;
4
+
5
+import java.io.ByteArrayOutputStream;
6
+import java.io.IOException;
7
+import java.io.UnsupportedEncodingException;
8
+import java.net.MalformedURLException;
9
+import java.net.URL;
10
+import java.net.URLEncoder;
11
+import java.nio.charset.Charset;
12
+import java.security.*;
13
+import java.security.spec.InvalidKeySpecException;
14
+import java.security.spec.PKCS8EncodedKeySpec;
15
+import java.util.Date;
16
+import java.util.Map;
17
+import java.util.TreeMap;
18
+
19
+/**
20
+ * 参数签名算法工具类
21
+ */
22
+public class RSAUtils {
23
+
24
+    /**
25
+     * 获取当前的时间戳参数
26
+     * @return
27
+     */
28
+    public static String getRtick(){
29
+        long timestamp = System.currentTimeMillis();
30
+        int rnd = (int)Math.random() * 1000;
31
+        String rtick = timestamp + "" + rnd;
32
+        return rtick;
33
+    }
34
+
35
+    /**
36
+     * 计算参数签名
37
+     * @param developerId 开发者ID
38
+     * @param privateKey 用户私钥
39
+     * @param host 请求的HOST地址(http://ip:port/context)
40
+     * @param methodName 请求的接口方法名
41
+     * @param rtick 时间戳参数
42
+     * @param urlParams url参数(param1=value1&param2=value2&param3=value3)
43
+     * @param requestBody request body 参数(JSON字符串)
44
+     * @return
45
+     */
46
+    public static String calcRsaSign(String developerId, String privateKey, String host, String methodName, String rtick, String urlParams, String requestBody) {
47
+        String url = host+methodName;
48
+
49
+        Map<String, String> mySignedURLParams = new TreeMap<String, String>();
50
+        mySignedURLParams.put("developerId", developerId);
51
+        mySignedURLParams.put("rtick", rtick);
52
+        mySignedURLParams.put("signType", "rsa");
53
+
54
+        if(urlParams != null && !"".equals(urlParams)){
55
+            String[] params = urlParams.split("&");
56
+            for(String p1 : params){
57
+                String[] p2 = p1.split("=");
58
+                String key = p2[0];
59
+                String value = "";
60
+                if(p2.length == 2){
61
+                    value = p2[1];
62
+                }
63
+                mySignedURLParams.put(key, value);
64
+            }
65
+        }
66
+
67
+        String requestPath;
68
+        try {
69
+            requestPath = new URL(url).getPath();
70
+        }
71
+        catch (MalformedURLException e) {
72
+            throw new RuntimeException(e.getMessage(), e);
73
+        }
74
+
75
+        StringBuilder signStringBuilder = new StringBuilder();
76
+        for (String name : mySignedURLParams.keySet()) {
77
+            String value = mySignedURLParams.get(name);
78
+            signStringBuilder.append(name);
79
+            signStringBuilder.append("=");
80
+            signStringBuilder.append(value);
81
+        }
82
+        signStringBuilder.append(requestPath);
83
+
84
+        if (requestBody != null && !"".equals(requestBody) ) {
85
+            String requestMd5 = getRequestMd5(requestBody);
86
+            signStringBuilder.append(requestMd5);
87
+        }
88
+
89
+        String signString = signStringBuilder.toString();
90
+        String rsaSign =  calcRsaSign(privateKey, signString);
91
+        //rsa算出来的sign,需要urlencode
92
+        try {
93
+            rsaSign = URLEncoder.encode(rsaSign,"UTF-8");
94
+        } catch (UnsupportedEncodingException e) {
95
+            rsaSign = null;
96
+        }
97
+        return rsaSign;
98
+    }
99
+
100
+    /**
101
+     * 获取request body 的MD5
102
+     * @param requestBody
103
+     * @return
104
+     */
105
+    private static String getRequestMd5(final String requestBody) {
106
+        byte[] data;
107
+
108
+        String newRequestBody = convertToUtf8(requestBody);
109
+        try {
110
+            data = newRequestBody.getBytes("UTF-8");
111
+        }
112
+        catch (UnsupportedEncodingException e) {
113
+            throw new RuntimeException(e.getMessage(), e);
114
+        }
115
+        return md5(data);
116
+    }
117
+
118
+    /**
119
+     * 计算参数RSA签名
120
+     * @param privateKey
121
+     * @param signData
122
+     * @return
123
+     */
124
+    private static String calcRsaSign(String privateKey, final String signData) {
125
+        byte[] data;
126
+        try {
127
+            data = signData.getBytes("UTF-8");
128
+        }
129
+        catch (UnsupportedEncodingException e) {
130
+            throw new RuntimeException(e.getMessage(), e);
131
+        }
132
+        byte[] sign = null;
133
+        // 解密由base64编码的私钥
134
+        byte[] privateKeyBytes = base64decode(privateKey.getBytes());
135
+
136
+        // 构造PKCS8EncodedKeySpec对象
137
+        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(privateKeyBytes);
138
+
139
+        // KEY_ALGORITHM 指定的加密算法
140
+        KeyFactory keyFactory;
141
+        try {
142
+            keyFactory = KeyFactory.getInstance("RSA");
143
+        }
144
+        catch (NoSuchAlgorithmException e) {
145
+            throw new RuntimeException(e.getMessage(), e);
146
+        }
147
+
148
+        // 取私钥匙对象
149
+        PrivateKey priKey;
150
+        try {
151
+            priKey = keyFactory.generatePrivate(pkcs8KeySpec);
152
+        }
153
+        catch (InvalidKeySpecException e) {
154
+            throw new RuntimeException(e.getMessage(), e);
155
+        }
156
+
157
+        // 用私钥对信息生成数字签名
158
+        Signature signature;
159
+        try {
160
+            signature = Signature.getInstance("SHA1withRSA");
161
+        }
162
+        catch (NoSuchAlgorithmException e) {
163
+            throw new RuntimeException(e.getMessage(), e);
164
+        }
165
+        try {
166
+            signature.initSign(priKey);
167
+        }
168
+        catch (InvalidKeyException e) {
169
+            throw new RuntimeException(e.getMessage(), e);
170
+        }
171
+
172
+        try {
173
+            signature.update(data);
174
+            sign = signature.sign();
175
+        }
176
+        catch (SignatureException e) {
177
+            throw new RuntimeException(e.getMessage(), e);
178
+        }
179
+        return new String(base64encode(sign));
180
+    }
181
+
182
+    /**
183
+     * 转换字符集到utf8
184
+     *
185
+     * @param src
186
+     * @return
187
+     */
188
+    private static String convertToUtf8(String src) {
189
+        if (src == null || src.length() == 0) {
190
+            return src;
191
+        }
192
+        if ("UTF-8".equalsIgnoreCase(Charset.defaultCharset().name())) {
193
+            return src;
194
+        }
195
+
196
+        byte[] srcData = src.getBytes();
197
+        try {
198
+            return new String(srcData, "UTF-8");
199
+        }
200
+        catch (UnsupportedEncodingException e) {
201
+            throw new RuntimeException(e.getMessage(), e);
202
+        }
203
+    }
204
+
205
+    /**
206
+     * md5
207
+     * @param data
208
+     * @return
209
+     */
210
+    public static String md5(byte[] data) {
211
+        char hexDigits[]={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
212
+        byte[] btInput = data;
213
+        // 获得MD5摘要算法的 MessageDigest 对象
214
+        MessageDigest mdInst;
215
+        try {
216
+            mdInst = MessageDigest.getInstance("MD5");
217
+        }
218
+        catch (NoSuchAlgorithmException e) {
219
+            throw new RuntimeException(e.getMessage(), e);
220
+        }
221
+        // 使用指定的字节更新摘要
222
+        mdInst.update(btInput);
223
+        // 获得密文
224
+        byte[] md = mdInst.digest();
225
+        // 把密文转换成十六进制的字符串形式
226
+        int j = md.length;
227
+        char str[] = new char[j * 2];
228
+        int k = 0;
229
+        for (int i = 0; i < j; i++) {
230
+            byte byte0 = md[i];
231
+            str[k++] = hexDigits[byte0 >>> 4 & 0xf];
232
+            str[k++] = hexDigits[byte0 & 0xf];
233
+        }
234
+        return new String(str);
235
+    }
236
+
237
+    /**
238
+     * base64编码
239
+     * @param data
240
+     * @return
241
+     */
242
+    public static byte[] base64encode(byte[] data) {
243
+        return Base64.encodeBase64(data);
244
+    }
245
+    
246
+    /**
247
+     * base64编码字符串
248
+     * @param data
249
+     * @return
250
+     */
251
+    public static String base64encodeString(byte[] data) {
252
+        return Base64.encodeBase64String(data);
253
+    }
254
+    
255
+    /**
256
+     * base64解码
257
+     * @param data
258
+     * @return
259
+     */
260
+    public static byte[] base64decode(byte[] data) {
261
+        try {
262
+            return Base64.decodeBase64(data);
263
+        } catch (Exception e) {
264
+            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
265
+            for (int i = 0; i < data.length; i++) {
266
+                byte c = data[i];
267
+                if (c == 13 || c == 10) {
268
+                    continue;
269
+                }
270
+                outputStream.write(c);
271
+            }
272
+            try {
273
+                outputStream.close();
274
+            } catch (IOException e2) {
275
+
276
+            }
277
+            data = outputStream.toByteArray();
278
+            return Base64.decodeBase64(data);
279
+        }
280
+    }
281
+}