瀏覽代碼

http util

WangKang 7 月之前
父節點
當前提交
15aeb12bdc

+ 41 - 0
emoon-openplatform/pom.xml

@@ -0,0 +1,41 @@
+<?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>
+    <parent>
+        <groupId>org.dromara</groupId>
+        <artifactId>emoon-admin</artifactId>
+        <version>5.4.1</version>
+    </parent>
+
+    <artifactId>emoon-openplatform</artifactId>
+
+    <dependencies>
+        <dependency>
+            <groupId>org.springframework.boot</groupId>
+            <artifactId>spring-boot-starter-web</artifactId>
+        </dependency>
+
+        <!-- Jackson for JSON processing -->
+        <dependency>
+            <groupId>com.fasterxml.jackson.core</groupId>
+            <artifactId>jackson-databind</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.dromara</groupId>
+            <artifactId>ruoyi-common-core</artifactId>
+        </dependency>
+        <dependency>
+            <groupId>org.springframework.cloud</groupId>
+            <artifactId>spring-cloud-starter-openfeign</artifactId>
+        </dependency>
+    </dependencies>
+
+    <properties>
+        <maven.compiler.source>21</maven.compiler.source>
+        <maven.compiler.target>21</maven.compiler.target>
+        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+    </properties>
+
+</project>

+ 16 - 0
emoon-openplatform/src/main/java/com/emoon/openplatform/OpenPlatformApplication.java

@@ -0,0 +1,16 @@
+package com.emoon.openplatform;
+
+import org.springframework.boot.SpringApplication;
+import org.springframework.boot.autoconfigure.SpringBootApplication;
+
+/**
+ * @author destiny
+ * @description:
+ * @date 2025/9/23 17:36
+ */
+@SpringBootApplication
+public class OpenPlatformApplication {
+    public static void main(String[] args) {
+        SpringApplication.run(OpenPlatformApplication.class, args);
+    }
+}

+ 17 - 0
emoon-openplatform/src/main/java/com/emoon/openplatform/client/LocalTokenClient.java

@@ -0,0 +1,17 @@
+package com.emoon.openplatform.client;
+
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.PostMapping;
+
+/**
+ * @author destiny
+ * @description:
+ * @date 2025/9/24 21:58
+ */
+@FeignClient(name = "emoon-admin", url = "${emoon.admin.url-local}")
+public interface LocalTokenClient {
+
+    @PostMapping("/Apis/getToken")
+    String getToken(String token, String model, String network, String dataJson);
+
+}

+ 17 - 0
emoon-openplatform/src/main/java/com/emoon/openplatform/client/TokenClient.java

@@ -0,0 +1,17 @@
+package com.emoon.openplatform.client;
+
+import org.springframework.cloud.openfeign.FeignClient;
+import org.springframework.web.bind.annotation.PostMapping;
+
+/**
+ * @author destiny
+ * @description:
+ * @date 2025/9/24 21:52
+ */
+@FeignClient(name = "emoon-admin", url = "${emoon.admin.url}")
+public interface TokenClient {
+
+    @PostMapping("/Apis/getToken")
+    String getToken(String token, String model, String network, String dataJson);
+
+}

+ 139 - 0
emoon-openplatform/src/main/java/com/emoon/openplatform/controller/TokenController.java

@@ -0,0 +1,139 @@
+package com.emoon.openplatform.controller;
+
+import cn.hutool.http.HttpStatus;
+import com.emoon.openplatform.util.HttpUtil;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.dromara.common.core.domain.R;
+import org.dromara.common.core.utils.StringUtils;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.web.bind.annotation.*;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * @author destiny
+ * @description:
+ * @date 2025/9/23 17:44
+ */
+@Slf4j
+@RestController
+@RequestMapping("/Send")
+@CrossOrigin(origins = "*")
+public class TokenController {
+
+    public static final String NETWORK = "1";
+    public static final String NETWORK_LOCAL = "2";
+    @Value("${sm4.key}")
+    private String sm4Key;
+
+    @Value("${sm4.private-key}")
+    private String sm4PrivateKey;
+
+    @Value("${sm4.public-key}")
+    private String sm4PublicKey;
+
+    @Value("${sm4.open-url}")
+    private String sm4OpenUrl;
+
+    @Value("${sm4.open-url-local}")
+    private String sm4OpenUrlLocal;
+
+    @PostMapping("/dataSM4")
+    public R<String> getToken(@RequestParam(required = false, defaultValue = "") String token,
+                           @RequestParam String model,
+                           @RequestParam String network,
+                           @RequestParam("data") String dataJson) {
+        try {
+            String result = dataSM4(token, model, network, dataJson);
+            return R.ok(result);
+        } catch (Exception e) {
+            log.error("Failed to get token: {}", e.getMessage(), e);
+            return R.fail(HttpStatus.HTTP_INTERNAL_ERROR, "获取令牌失败: " + e.getMessage());
+        }
+    }
+    public String dataSM4(String token, String model, String network, String dataJson) throws Exception {
+        // 判断该请求是否需要生成token
+        if ("noUse".equals(token)) {
+            return "noToken";
+        }
+
+        // 组装请求的数据为base64格式
+        ObjectMapper objectMapper = new ObjectMapper();
+        Map<String, Object> data = new HashMap<>();
+        data.put("model", model);
+        data.put("network", network);
+
+        // 解析输入数据
+        Object inputData = objectMapper.readValue(dataJson, Object.class);
+        data.put("input", inputData);
+
+        String jsonData = objectMapper.writeValueAsString(data);
+        System.out.println("参数标记: " + jsonData);
+
+        // Base64编码
+        String base64Data = Base64.getEncoder().encodeToString(jsonData.getBytes(StandardCharsets.UTF_8));
+
+        // 对请求的参数进行SM4加密
+
+        byte[] encryptedBinary = sm4Encrypt(base64Data, sm4PrivateKey, sm4Key);
+        String encryptedBase64 = Base64.getEncoder().encodeToString(encryptedBinary);
+
+        // 创建最终的含有SM4的IV的数据
+        Map<String, String> modifiedDataMap = new HashMap<>();
+        modifiedDataMap.put("encryptedBase64", encryptedBase64);
+        modifiedDataMap.put("smIV", sm4Key);
+        modifiedDataMap.put("publicKey", sm4PublicKey);
+
+        String modifiedDataJson = objectMapper.writeValueAsString(modifiedDataMap);
+        String modifiedDataBase64 = Base64.getEncoder().encodeToString(modifiedDataJson.getBytes(StandardCharsets.UTF_8));
+
+        // 将 '+' 替换为 '-','/' 替换为 '_'
+        String modifiedData = modifiedDataBase64.replace('+', '-').replace('/', '_');
+
+        // 将加密的参数发送给开放平台,获取短令牌
+        String url;
+        if (StringUtils.equals(NETWORK, network)) {
+            url = sm4OpenUrl + "/Apis/getToken";
+        } else if (StringUtils.equals(NETWORK_LOCAL, network)) {
+            url = sm4OpenUrlLocal + "/Apis/getToken";
+        } else {
+            throw new IllegalArgumentException("Invalid network parameter");
+        }
+
+
+
+        Map<String, String> encryption = new HashMap<>();
+        encryption.put("information", modifiedData);
+
+        String response = HttpUtil.curlPost(url, encryption);
+        // 解析响应获取token(这里简化处理,实际应使用JSON解析库)
+        // 假设响应格式为 {"token":"xxx","code":0}
+
+        return parseTokenFromResponse(response);
+    }
+
+    // 简化的响应解析方法
+    private String parseTokenFromResponse(String response) {
+        // 实际应该使用JSON解析库如Jackson或Gson
+        // 这里简化处理,假设响应格式为 {"token":"xxx","code":0}
+        int start = response.indexOf("\"token\":\"") + 9;
+        int end = response.indexOf("\"", start);
+        return response.substring(start, end);
+    }
+
+    // SM4加密方法(使用AES算法模拟SM4)
+    private byte[] sm4Encrypt(String data, String key, String iv) throws Exception {
+        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
+        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "AES");
+        IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
+        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
+        return cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
+    }
+}

+ 158 - 0
emoon-openplatform/src/main/java/com/emoon/openplatform/util/HttpUtil.java

@@ -0,0 +1,158 @@
+package com.emoon.openplatform.util;
+
+import com.fasterxml.jackson.databind.ObjectMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.http.*;
+import org.springframework.util.LinkedMultiValueMap;
+import org.springframework.util.MultiValueMap;
+import org.springframework.web.client.RestClientException;
+import org.springframework.web.client.RestTemplate;
+
+import java.util.Map;
+
+/**
+ * @author destiny
+ * @description: HTTP工具类,提供POST请求功能
+ * @date 2025/9/23 18:07
+ */
+@Slf4j
+public class HttpUtil {
+    private static final RestTemplate restTemplate = new RestTemplate();
+    private static final ObjectMapper objectMapper = new ObjectMapper();
+
+    /**
+     * 模拟PHP中的curlPost函数 - 发送POST请求
+     *
+     * @param url  请求URL
+     * @param data 请求数据
+     * @return 响应内容
+     */
+    public static String curlPost(String url, Map<String, String> data) {
+        return curlPost(url, data, null, false);
+    }
+
+    /**
+     * 模拟PHP中的curlPost函数 - 发送POST请求
+     *
+     * @param url     请求URL
+     * @param data    请求数据
+     * @param headers 请求头
+     * @return 响应内容
+     */
+    public static String curlPost(String url, Map<String, String> data, Map<String, String> headers) {
+        return curlPost(url, data, headers, false);
+    }
+
+    /**
+     * 模拟PHP中的curlPost函数 - 发送POST请求
+     *
+     * @param url     请求URL
+     * @param data    请求数据
+     * @param headers 请求头
+     * @param isJson  是否以JSON格式发送
+     * @return 响应内容
+     */
+    public static String curlPost(String url, Map<String, String> data, Map<String, String> headers, boolean isJson) {
+        try {
+            HttpEntity<?> requestEntity = buildRequestEntity(data, headers, isJson);
+            ResponseEntity<String> response = restTemplate.exchange(
+                url,
+                HttpMethod.POST,
+                requestEntity,
+                String.class
+            );
+            return response.getBody();
+        } catch (Exception e) {
+            return handleException(e);
+        }
+    }
+
+    /**
+     * 重载方法:用于发送JSON对象而不是Map
+     */
+    public static String curlPost(String url, Object dataObject, Map<String, String> headers, boolean isJson) {
+        try {
+            HttpEntity<?> requestEntity = buildRequestEntity(dataObject, headers, isJson);
+            ResponseEntity<String> response = restTemplate.exchange(
+                url,
+                HttpMethod.POST,
+                requestEntity,
+                String.class
+            );
+            return response.getBody();
+        } catch (Exception e) {
+            return handleException(e);
+        }
+    }
+
+    /**
+     * 构建请求实体
+     */
+    private static HttpEntity<?> buildRequestEntity(Object data, Map<String, String> headers, boolean isJson) {
+        HttpHeaders httpHeaders = new HttpHeaders();
+
+        // 设置请求头
+        if (headers != null && !headers.isEmpty()) {
+            headers.forEach(httpHeaders::set);
+        }
+
+        if (isJson) {
+            // JSON格式发送
+            httpHeaders.setContentType(MediaType.APPLICATION_JSON);
+            String jsonData = toJson(data);
+            return new HttpEntity<>(jsonData, httpHeaders);
+        } else {
+            // 表单格式发送
+            httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
+            MultiValueMap<String, String> formData = toFormData(data);
+            return new HttpEntity<>(formData, httpHeaders);
+        }
+    }
+
+    /**
+     * 将对象转换为JSON字符串
+     */
+    private static String toJson(Object data) {
+        try {
+            return objectMapper.writeValueAsString(data);
+        } catch (Exception e) {
+            throw new RuntimeException("Failed to convert object to JSON", e);
+        }
+    }
+
+    /**
+     * 将对象转换为表单数据
+     */
+    @SuppressWarnings("unchecked")
+    private static MultiValueMap<String, String> toFormData(Object data) {
+        MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
+
+        if (data == null) {
+            return formData;
+        }
+
+        if (data instanceof Map) {
+            ((Map<String, String>) data).forEach((key, value) ->
+                formData.add(String.valueOf(key), value != null ? value.toString() : ""));
+        } else { // 对于普通对象,可以考虑使用objectMapper转换为Map再处理
+            try {
+                Map<String, Object> map = objectMapper.convertValue(data, Map.class);
+                map.forEach((key, value) ->
+                    formData.add(key, value != null ? value.toString() : ""));
+            } catch (Exception e) {
+                // 如果转换失败,添加对象的toString表示
+                formData.add("data", data.toString());
+            }
+        }
+
+        return formData;
+    }
+
+    /**
+     * 统一异常处理
+     */
+    private static String handleException(Exception e) {
+        e.printStackTrace();
+        return "{\"error\":\"" + e.getMessage() + "\"}";
+    }
+}

+ 14 - 0
emoon-openplatform/src/main/resources/application.yml

@@ -0,0 +1,14 @@
+server:
+  port: 8081
+
+sm4:
+  key: 1234567890123456
+  public-key: ZpX4mTkcNwL58qAhFD1bEy7vRCMzxgKQ
+  private-key: aX7pKf2LtQ9sVmZ3
+  open-url: http://8.137.127.56:3340
+  open-url-local: http://192.168.1.8:3338
+
+emoon:
+  admin:
+    url: http://8.137.127.56:3340
+    url-local: http://192.168.1.8:3338

+ 13 - 0
pom.xml

@@ -365,6 +365,18 @@
                 <type>pom</type>
                 <scope>import</scope>
             </dependency>
+
+            <dependency>
+                <groupId>org.apache.tika</groupId>
+                <artifactId>tika-parsers-standard-package</artifactId>
+                <version>2.9.1</version>
+            </dependency>
+
+            <dependency>
+                <groupId>org.springframework.cloud</groupId>
+                <artifactId>spring-cloud-starter-openfeign</artifactId>
+                <version>4.0.4</version>
+            </dependency>
         </dependencies>
     </dependencyManagement>
 
@@ -373,6 +385,7 @@
         <module>ruoyi-common</module>
         <module>ruoyi-extend</module>
         <module>ruoyi-modules</module>
+        <module>emoon-openplatform</module>
     </modules>
     <packaging>pom</packaging>
 

+ 0 - 1
ruoyi-modules/ruoyi-system/pom.xml

@@ -132,7 +132,6 @@
         <dependency>
             <groupId>org.apache.tika</groupId>
             <artifactId>tika-parsers-standard-package</artifactId>
-            <version>2.9.1</version>
         </dependency>
         <dependency>
             <groupId>org.springframework.boot</groupId>