zj
2024-06-03 5668aa7dc743d930b4b09dce1e7ccbba371e93cf
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
package org.example.ssmico.demos.web.util;
 
import cn.hutool.core.convert.Convert;
import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.*;
import org.example.ssmico.demos.web.dto.ResultDto;
 
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;
import java.util.stream.Collectors;
 
public class RsaSigner {
 
    public String genSign(Map<String, Object> data, String priKey) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException {
        Map<String, String> stringMap = toStringMap(new GsonBuilder().create().toJson(data));
        return this.sign(this.genSignString(stringMap), priKey);
    }
 
    public String genSignString(Map<String, String> params) {
        if (null == params || params.size() == 0) {
            return "";
        }
 
        List<String> sortedKeys = new ArrayList<>(params.keySet());
        sortedKeys.remove("sign");
        sortedKeys.sort(null);
        String sb = sortedKeys.stream().map(s -> s + "=" + params.get(s)).collect(Collectors.joining("&"));
 
        System.out.println("genSignString = " + sb);
 
        return sb;
    }
 
    public String sign(String str, String priKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.getDecoder().decode(priKey.getBytes(StandardCharsets.UTF_8));
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        PrivateKey pk = keyFactory.generatePrivate(keySpec);
 
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(pk);
        signature.update(str.getBytes(StandardCharsets.UTF_8));
        return new String(Base64.getEncoder().encode(signature.sign()), StandardCharsets.UTF_8);
    }
 
    public boolean verifySign(JsonElement data, String sign, String pubKey) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
        Map<String, String> resMap = toStringMap(data);
        String signString = this.genSignString(resMap);
 
        byte[] keyBytes = Base64.getDecoder().decode(pubKey.getBytes(StandardCharsets.UTF_8));
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey key = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(key);
        signature.update(signString.getBytes(StandardCharsets.UTF_8));
        return signature.verify(Base64.getDecoder().decode(sign.getBytes(StandardCharsets.UTF_8)));
    }
 
    public Map<String, String> toStringMap(String str) {
        JsonParser jp = new JsonParser();
        JsonElement jEle = jp.parse(str);
        return toStringMap(jEle);
    }
 
    public static Map<String, String> toStringMap(JsonElement jEle) {
        Map<String, String> resMap = new HashMap<>();
        if (null != jEle && jEle.isJsonObject()) {
            for (Map.Entry<String, JsonElement> entry : jEle.getAsJsonObject().entrySet()) {
                resMap.put(entry.getKey(), valueAsString(entry.getValue()));
            }
        }
        return resMap;
    }
 
    public static String valueAsString(JsonElement element) {
        if (element.isJsonNull()) {
            return "";
        } else if (element.isJsonPrimitive()) {
            return element.getAsJsonPrimitive().getAsString();
        } else if (element.isJsonObject()) {
            StringBuilder sb = new StringBuilder();
            for (Map.Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) {
                sb.append(valueAsString(entry.getValue()));
            }
            return sb.toString();
        } else if (element.isJsonArray()) {
            StringBuilder sb = new StringBuilder();
            for (JsonElement vv : element.getAsJsonArray()) {
                sb.append(valueAsString(vv));
            }
            return sb.toString();
        }
        return "";
    }
 
    public static String doPost(String httpUrl, String param) {
        URL url = null;
        HttpURLConnection connection = null;
        InputStream is = null;
        OutputStream os = null;
        String result = "";
 
        try {
            url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
 
            if (connection instanceof HttpsURLConnection) {
                SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[]{new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
 
                    @Override
                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {}
 
                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                }}, new SecureRandom());
                ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory());
                ((HttpsURLConnection) connection).setHostnameVerifier((hostname, session) -> true);
            }
 
            connection.setRequestMethod("POST");
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setRequestProperty("Content-Type", "application/json");
 
            os = connection.getOutputStream();
            os.write(param.getBytes());
            os.flush();
 
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                is = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    result += line;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
                if (connection != null) {
                    connection.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
        return result;
    }
}