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 data, String priKey) throws NoSuchAlgorithmException, InvalidKeySpecException, SignatureException, InvalidKeyException { Map stringMap = toStringMap(new GsonBuilder().create().toJson(data)); return this.sign(this.genSignString(stringMap), priKey); } public String genSignString(Map params) { if (null == params || params.size() == 0) { return ""; } List 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 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 toStringMap(String str) { JsonParser jp = new JsonParser(); JsonElement jEle = jp.parse(str); return toStringMap(jEle); } public static Map toStringMap(JsonElement jEle) { Map resMap = new HashMap<>(); if (null != jEle && jEle.isJsonObject()) { for (Map.Entry 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 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; } }