zyl 3 mesi fa
commit
f5b0d8e16a
5 ha cambiato i file con 414 aggiunte e 0 eliminazioni
  1. 38 0
      .gitignore
  2. 39 0
      pom.xml
  3. 114 0
      src/main/java/test.java
  4. 108 0
      src/main/java/utils/HttpRequest.java
  5. 115 0
      src/main/java/utils/SignUtils.java

+ 38 - 0
.gitignore

@@ -0,0 +1,38 @@
+target/
+!.mvn/wrapper/maven-wrapper.jar
+!**/src/main/**/target/
+!**/src/test/**/target/
+
+### IntelliJ IDEA ###
+.idea/modules.xml
+.idea/jarRepositories.xml
+.idea/compiler.xml
+.idea/libraries/
+*.iws
+*.iml
+*.ipr
+
+### Eclipse ###
+.apt_generated
+.classpath
+.factorypath
+.project
+.settings
+.springBeans
+.sts4-cache
+
+### NetBeans ###
+/nbproject/private/
+/nbbuild/
+/dist/
+/nbdist/
+/.nb-gradle/
+build/
+!**/src/main/**/build/
+!**/src/test/**/build/
+
+### VS Code ###
+.vscode/
+
+### Mac OS ###
+.DS_Store

+ 39 - 0
pom.xml

@@ -0,0 +1,39 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+    <modelVersion>4.0.0</modelVersion>
+
+    <groupId>com.citygis</groupId>
+    <artifactId>cdc_encryption</artifactId>
+    <version>1.0-SNAPSHOT</version>
+
+    <properties>
+        <maven.compiler.source>8</maven.compiler.source>
+        <maven.compiler.target>8</maven.compiler.target>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+    <dependencies>
+        <dependency>
+            <groupId>com.alibaba.fastjson2</groupId>
+            <artifactId>fastjson2</artifactId>
+            <version>2.0.43</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.projectlombok</groupId>
+            <artifactId>lombok</artifactId>
+            <version>1.18.32</version>
+        </dependency>
+
+        <dependency>
+            <groupId>org.apache.httpcomponents</groupId>
+            <artifactId>httpclient</artifactId>
+            <version>4.5.13</version> <!-- 可以使用最新版本 -->
+        </dependency>
+
+
+    </dependencies>
+
+</project>

+ 114 - 0
src/main/java/test.java

@@ -0,0 +1,114 @@
+import com.alibaba.fastjson2.JSONObject;
+import utils.SignUtils;
+
+import java.io.FileInputStream;
+import java.security.MessageDigest;
+
+/**
+ * @Author: zyl
+ * @CreateTime: 2024-12-10
+ * @Description:
+ * @Version: 1.0
+ */
+public class test {
+
+    public static void main(String[] args) {
+        try {
+            // 签名
+            String sign = null;
+            String respType = null;
+            String utf8String = "123";
+            JSONObject resultJson = SignUtils.getSign(utf8String, "test");
+            if(resultJson==null){
+                System.out.println("获取签名错误!");
+            }else{
+                JSONObject responseJson = resultJson.getJSONObject("response");
+                sign = responseJson.getString("signature");
+                respType = resultJson.getString("respType");
+                System.out.println("签名值为:"+sign);
+                System.out.println("签名响应格式:"+respType);
+            }
+            //验签
+            if(!StringUtils.isEmpty(sign) && !StringUtils.isEmpty(respType) ){
+                JSONObject verfityResultJson = SignUtils.verifySign(respType, sign.replaceAll(" ","+"), utf8String, "test");
+                if(verfityResultJson==null){
+                    System.out.println("验签错误!");
+                }else{
+                    JSONObject responseJson = resultJson.getJSONObject("response");
+                    if(!StringUtils.isEmpty(responseJson.getString("respValue")) && responseJson.getString("respValue").equals("0")){
+                        System.out.println("验签成功!");
+                    }else{
+                        System.out.println("验签失败!");
+                    }
+                }
+            }
+
+
+        } catch (Exception e) {
+            System.out.println(e.getMessage());
+        }
+    }
+
+    public static void main(String[] args) {
+        try {
+            // 文件签名
+            String sign = null;
+            String respType = null;
+            String filePath = "/etc/passwd";
+            String utf8String = getFileHash(filePath);
+            JSONObject resultJson = SignUtils.getSign(utf8String, "test");
+
+            if(resultJson==null){
+                System.out.println("获取签名错误!");
+            }else{
+                JSONObject responseJson = resultJson.getJSONObject("response");
+                sign = responseJson.getString("signature");
+                respType = resultJson.getString("respType");
+                System.out.println("签名值为:"+sign);
+                System.out.println("签名响应格式:"+respType);
+            }
+
+            //文件验签
+            if(!StringUtils.isEmpty(sign) && !StringUtils.isEmpty(respType) ){
+                JSONObject verfityResultJson = SignUtils.verifySign(respType, sign.replaceAll(" ","+"), utf8String, "test");
+                if(verfityResultJson==null){
+                    System.out.println("验签错误!");
+                }else{
+                    JSONObject responseJson = resultJson.getJSONObject("response");
+                    if(!StringUtils.isEmpty(responseJson.getString("respValue")) && responseJson.getString("respValue").equals("0")){
+                        System.out.println("验签成功!");
+                    }else{
+                        System.out.println("验签失败!");
+                    }
+                }
+            }
+
+        } catch (Exception e) {
+            System.out.println(e.getMessage());
+        }
+    }
+    // 获取文件hash
+    public String getFileHash(String path){
+
+        StringBuffer sb = new StringBuffer();
+        try {
+            MessageDigest md = MessageDigest.getInstance("MD5");
+            FileInputStream fis = new FileInputStream(path);
+            byte[] buff = new byte[8192];
+            int length;
+            while((length = fis.read(buff))!=-1){
+                md.update(buff,0 , length);
+            }
+            fis.close();
+            byte[] digest = md.digest();
+
+            for(byte b :digest){
+                sb.append(String.format("%02x",b));
+            }
+        }catch (Exception e){
+            e.printStackTrace();
+        }
+
+        return sb.toString();
+    }
+}

+ 108 - 0
src/main/java/utils/HttpRequest.java

@@ -0,0 +1,108 @@
+package utils;
+
+import com.alibaba.fastjson2.JSONObject;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.http.HttpStatus;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpPost;
+import org.apache.http.conn.ssl.NoopHostnameVerifier;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.conn.ssl.TrustStrategy;
+import org.apache.http.entity.ContentType;
+import org.apache.http.entity.StringEntity;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.ssl.SSLContextBuilder;
+import org.apache.http.util.EntityUtils;
+
+import javax.net.ssl.HostnameVerifier;
+import javax.net.ssl.SSLContext;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.security.KeyManagementException;
+import java.security.KeyStoreException;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * @Author: zyl
+ * @CreateTime: 2024-12-10
+ * @Description:
+ * @Version: 1.0
+ */
+@Slf4j
+public class HttpRequest {
+
+
+    /**
+     * post请求传输json数据
+     *
+     * @param url
+     * @param json
+     * @param encoding
+     * @return
+     * @throws ClientProtocolException
+     * @throws IOException
+     */
+    public static String sendPostDataByJson(String url, String json, String encoding) throws ClientProtocolException, IOException {
+        String result = "";
+
+
+        // 创建httpclient对象
+        CloseableHttpClient httpClient = createSSLClientDefault();
+
+        // 创建post方式请求对象
+        HttpPost httpPost = new HttpPost(url);
+
+        // 设置参数到请求对象中
+        StringEntity stringEntity = new StringEntity(json, ContentType.APPLICATION_JSON);
+        stringEntity.setContentEncoding("utf-8");
+        httpPost.setEntity(stringEntity);
+
+        // 执行请求操作,并拿到结果(同步阻塞)
+        CloseableHttpResponse response = httpClient.execute(httpPost);
+
+        // 获取结果实体
+        // 判断网络连接状态码是否正常(0--200都数正常)
+        log.error("wanDaStatusCode : " + response.getStatusLine().getStatusCode());
+        log.error("wanDaStatusEntity : " + response.getEntity());
+        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
+            result = EntityUtils.toString(response.getEntity(), "utf-8");
+        }
+//        log.error("wanDaResult : " + EntityUtils.toString(response.getEntity(), "utf-8"));
+        httpClient.close();
+        // 释放链接
+        response.close();
+
+        return result;
+    }
+
+    // 创建自定义的 SSL 上下文,用于绕过证书验证
+    public static CloseableHttpClient createSSLClientDefault() {
+        try {
+            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
+                // 信任所有证书
+                public boolean isTrusted(X509Certificate[] arg0, String arg1)
+                        throws CertificateException {
+                    return true;
+                }
+            }).build();
+            // 创建主机名验证器,用于绕过主机名验证
+            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
+            // 创建 SSL 连接套接字工厂,将自定义的 SSL 上下文和主机名验证器应用于 HTTPS 连接
+            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
+            // 创建自定义的 CloseableHttpClient 实例,将 SSL 连接套接字工厂应用于 HTTP 客户端
+            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
+        } catch (KeyManagementException e) {
+            e.printStackTrace();
+        } catch (NoSuchAlgorithmException e) {
+            e.printStackTrace();
+        } catch (KeyStoreException e) {
+            e.printStackTrace();
+        }
+        return HttpClients.createDefault();
+    }
+}

+ 115 - 0
src/main/java/utils/SignUtils.java

@@ -0,0 +1,115 @@
+package utils;
+
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import com.sun.org.slf4j.internal.Logger;
+import com.sun.org.slf4j.internal.LoggerFactory;
+
+import java.io.IOException;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @Author: zyl
+ * @CreateTime: 2024-12-10
+ * @Description:
+ * @Version: 1.0
+ */
+public class SignUtils {
+
+    public static Logger logger = LoggerFactory.getLogger(SignUtils.class);
+    // 签名验签服务URL
+    private static final String URL = "http://172.22.112.56:8088";
+    // 签名验签厂商提供的认证code
+    private static final String AUTH_CODE = "";
+
+    // 获取签名
+    public static JSONObject getSign(String jsonString, String createBy) throws IOException {
+        String url = URL + "/svs-server/svsServer/bizSign/sign";
+        System.out.println("url: " + url);
+        Map<String, Object> map = new HashMap<String, Object>();
+        map.put("inData", jsonString);
+        map.put("authCode", AUTH_CODE);
+        map.put("reqType", 2);
+        map.put("createBy", createBy);
+        map.put("crl", false);
+        map.put("certificateChain", false);
+        map.put("originalText", false);
+        map.put("reqTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));
+
+        System.out.println(JSON.toJSONString(map));
+
+        String result = HttpRequest.sendPostDataByJson(url, JSON.toJSONString(map), null);
+        logger.error("wandaResult: " + result);
+        if (!JSONObject.isValid(result)) {
+            return null;
+        }
+        JSONObject jsonObject = JSONObject.parseObject(FinalUtils.handleJsonString(result));
+        JSONObject responseJson = jsonObject.getJSONObject("response");
+        logger.error("wandaResult responseJson: " + jsonObject);
+        if (StringUtils.isEmpty(responseJson.getString("respValue")) || !responseJson.getString("respValue").equals("0")) {
+            return null;
+        }
+        return jsonObject;
+    }
+
+    //验签 创建人为空
+    public static JSONObject verifySign(String respType, String sign, String jsonString) throws IOException {
+        String url = URL + "/svs-server/svsServer/bizSign/verifySign";
+        Map<String, Object> map = new HashMap<String, Object>();
+        map.put("authCode", AUTH_CODE);
+        if ("3".equals(respType)) { // P7 不带原文时必传,P7 带原文可以不传
+            map.put("inData", jsonString);
+        }
+        map.put("reqType", 2);
+        map.put("signature", sign);
+        map.put("cert", "");
+        map.put("verifyLevel", 0);
+        map.put("createBy", "");
+        map.put("reqTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));
+
+        System.out.println(JSON.toJSONString(map));
+
+        String result = HttpRequest.sendPostDataByJson(url, JSON.toJSONString(map), null);
+        logger.error("wandaResult: " + result);
+        if (!JSONObject.isValid(result)) {
+            return null;
+        }
+        JSONObject jsonObject = JSONObject.parseObject(FinalUtils.handleJsonString(result));
+        JSONObject responseJson = jsonObject.getJSONObject("response");
+        if (StringUtils.isEmpty(responseJson.getString("respValue")) || !responseJson.getString("respValue").equals("0")) {
+            return null;
+        }
+        return jsonObject;
+    }
+
+    //验签 包含创建人不为空
+    public static JSONObject verifySign(String respType, String sign, String jsonString, String createBy) throws IOException {
+        String url = URL + "/svs-server/svsServer/bizSign/verifySign";
+        Map<String, Object> map = new HashMap<String, Object>();
+        map.put("authCode", AUTH_CODE);
+        if ("3".equals(respType)) { // P7 不带原文时必传,P7 带原文可以不传
+            map.put("inData", jsonString);
+        }
+        map.put("reqType", 2);
+        map.put("signature", sign);
+        map.put("cert", "");
+        map.put("verifyLevel", 0);
+        map.put("createBy", createBy);
+        map.put("reqTime", DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD_HH_MM_SS, DateUtils.getNowDate()));
+
+        System.out.println(JSON.toJSONString(map));
+
+        String result = HttpRequest.sendPostDataByJson(url, JSON.toJSONString(map), null);
+        logger.error("wandaResult: " + result);
+        if (!JSONObject.isValid(result)) {
+            return null;
+        }
+        JSONObject jsonObject = JSONObject.parseObject(FinalUtils.handleJsonString(result));
+        JSONObject responseJson = jsonObject.getJSONObject("response");
+        if (StringUtils.isEmpty(responseJson.getString("respValue")) || !responseJson.getString("respValue").equals("0")) {
+            return null;
+        }
+        return jsonObject;
+    }
+}