From 670d895ebdedd89861fc0177be703f026b3ce625 Mon Sep 17 00:00:00 2001
From: hejianhao <15708179461@qq.com>
Date: 星期四, 08 五月 2025 15:14:33 +0800
Subject: [PATCH] 接口加密

---
 laboratory/src/utils/baseurl.js    |    2 
 laboratory/src/utils/request.js    |   38 +++++++++++++------
 laboratory/src/utils/sm4.js        |   14 +++++++
 laboratory/src/utils/encryption.js |   34 +++++++++++++++++
 laboratory/vue.config.js           |    4 +-
 laboratory/package.json            |    3 +
 6 files changed, 79 insertions(+), 16 deletions(-)

diff --git a/laboratory/package.json b/laboratory/package.json
index c6a3399..490395d 100644
--- a/laboratory/package.json
+++ b/laboratory/package.json
@@ -3,7 +3,7 @@
   "version": "0.1.0",
   "private": true,
   "scripts": {
-    "serve:dev": "cross-env VUE_APP_ENV=development vue-cli-service serve --port 8087",
+    "serve:dev": "cross-env VUE_APP_ENV=development vue-cli-service serve --port 8090",
     "serve:prod": "cross-env VUE_APP_ENV=production vue-cli-service serve",
     "build:dev": "cross-env VUE_APP_ENV=development vue-cli-service build",
     "build:prod": "cross-env VUE_APP_ENV=production vue-cli-service build",
@@ -16,6 +16,7 @@
     "core-js": "^3.41.0",
     "element-ui": "^2.15.6",
     "moment": "^2.30.1",
+    "sm-crypto": "^0.3.13",
     "vue": "^2.7.16",
     "vue-router": "^3.6.5",
     "vuex": "^3.6.2"
diff --git a/laboratory/src/utils/baseurl.js b/laboratory/src/utils/baseurl.js
index c3bfa75..b1e8ea6 100644
--- a/laboratory/src/utils/baseurl.js
+++ b/laboratory/src/utils/baseurl.js
@@ -1,7 +1,7 @@
 const apiConfig = {
     // 开发环境
     development: {
-        baseURL: "http://192.168.110.34:8081/",
+        baseURL: "http://192.168.110.34:8081",
         imgUrl: "",
     },
     // 生产环境
diff --git a/laboratory/src/utils/encryption.js b/laboratory/src/utils/encryption.js
new file mode 100644
index 0000000..4a01204
--- /dev/null
+++ b/laboratory/src/utils/encryption.js
@@ -0,0 +1,34 @@
+import axios from 'axios'
+import apiConfig from './baseurl'
+
+let encryptionKey = '2022lab02ora12to' // 默认密钥
+
+// 从接口获取密钥
+export const fetchEncryptionKey = async () => {
+    try {
+        const response = await axios.get(`${apiConfig.baseURL}/api/system/getEncryptionKey`)
+        if (response.data && response.data.code === 200) {
+            // 转换为Buffer并验证字节长度
+            const keyBuffer = Buffer.from(response.data.data, 'utf-8')
+            
+            if (keyBuffer.length !== 16) {
+                console.warn('无效密钥长度,使用默认密钥')
+                return encryptionKey // 保持原有密钥
+            }
+            
+            // 存储原始字符串和Buffer两种格式
+            encryptionKey = response.data.data
+            return encryptionKey
+        }
+    } catch (error) {
+        console.error('获取加密密钥失败:', error)
+    }
+}
+
+// 新增方法获取Buffer格式的密钥
+export const getEncryptionKeyBuffer = () => {
+    return Buffer.from(encryptionKey, 'utf-8')
+}
+
+// 获取当前密钥(保持字符串格式)
+export const getEncryptionKey = () => encryptionKey
\ No newline at end of file
diff --git a/laboratory/src/utils/request.js b/laboratory/src/utils/request.js
index 112b18c..f1d1c11 100644
--- a/laboratory/src/utils/request.js
+++ b/laboratory/src/utils/request.js
@@ -1,13 +1,10 @@
 import axios from 'axios'
 import apiConfig from './baseurl'
-
-import {
-  Message
-} from 'element-ui'
-
+import { Message } from 'element-ui'
+import { encryptBySM4, decryptBySM4 } from './sm4'  // 添加decryptBySM4
 
 const service = axios.create({
-  baseURL: apiConfig.baseURL,
+  // baseURL: apiConfig.baseURL,
   withCredentials: false, // 当跨域请求时发送cookie
   timeout: 30000, // request timeout
 })
@@ -16,6 +13,10 @@
 service.interceptors.request.use(
   config => {
     config['headers']['Authorization'] = `${sessionStorage.getItem('token')}`
+
+    // 判断是否需要加密(只对/api开头的请求进行加密)
+    const needEncrypt = config.url.startsWith('/api');
+
     if (config.method == 'get') {
       if (!config.params) config.params = {};
       config.params = {
@@ -24,8 +25,8 @@
     }
     if (config.method == 'post') {
       if (!config.data) config.data = {};
-      config.data = {
-        ...config.data,
+      if (needEncrypt) {
+        config.data = { param: encryptBySM4(config.data) };
       }
     }
     return config
@@ -42,11 +43,24 @@
       return
     }
     const res = response;
-    if (res.data.code == 200) {
-      if (!res.data.data) {
-        return Promise.resolve({...res.data})
+
+    // 新增解密处理:仅处理/api路径的POST响应
+    if (res.config.method === 'post' && res.config.url.startsWith('/api')) {
+      try {
+        if (res.data && res.data.data) {
+          // 这里假设使用decryptBySM4进行解密
+          res.data.data = decryptBySM4(res.data.data);
+        }
+      } catch (e) {
+        console.error('数据解密失败:', e);
       }
-      return Promise.resolve(res.data.data)
+    }
+
+    if (res.data.code == 200) {
+      if (!res.data) {
+        return Promise.resolve({})
+      }
+      return Promise.resolve(res.data)
     } else {
       if (res.data.code == 103 || res.data.code == 401) {
         Message({
diff --git a/laboratory/src/utils/sm4.js b/laboratory/src/utils/sm4.js
new file mode 100644
index 0000000..8f944dd
--- /dev/null
+++ b/laboratory/src/utils/sm4.js
@@ -0,0 +1,14 @@
+import { sm4 } from 'sm-crypto';
+import { getEncryptionKey, fetchEncryptionKey, getEncryptionKeyBuffer } from './encryption';
+
+// SM4加密函数
+export const encryptBySM4 = (data) => {
+    const key = getEncryptionKeyBuffer(); // 获取当前密钥
+    return sm4.encrypt(JSON.stringify(data), key);
+};
+
+// SM4解密函数
+export const decryptBySM4 = (data) => {
+    const key = getEncryptionKeyBuffer(); // 获取当前密钥
+    return JSON.parse(sm4.decrypt(data, key));
+};
\ No newline at end of file
diff --git a/laboratory/vue.config.js b/laboratory/vue.config.js
index da87678..8843269 100644
--- a/laboratory/vue.config.js
+++ b/laboratory/vue.config.js
@@ -10,11 +10,11 @@
         disableHostCheck: true, //禁用主机检查 
         proxy: {
             "/api": { // 设置以什么前缀开头的请求用来代理
-                target: "http://localhost:8080", //要访问的跨域的域名
+                target: "http://192.168.110.34:8081", //要访问的跨域的域名
                 secure: false, // 使用的是http协议则设置为false,https协议则设置为true
                 changOrigin: true, //开启代理
                 pathRewrite: {
-                    "^/api": "",
+                    "^/api": "/api",
                 },
             },
         },

--
Gitblit v1.7.1