加密功能添加

This commit is contained in:
cwchen 2025-09-04 10:10:54 +08:00
parent bedf4a59d4
commit 3320a56495
18 changed files with 323 additions and 1197 deletions

View File

@ -1,10 +1,10 @@
# 页面标题 # 页面标题
VUE_APP_TITLE = 若依管理系统 VUE_APP_TITLE = 工程档案资料移交管理系统
# 开发环境配置 # 开发环境配置
ENV = 'development' ENV = 'development'
# 若依管理系统/开发环境 # 工程档案资料移交管理系统/开发环境
VUE_APP_BASE_API = '/dev-api' VUE_APP_BASE_API = '/dev-api'
# 路由懒加载 # 路由懒加载

View File

@ -1,8 +1,8 @@
# 页面标题 # 页面标题
VUE_APP_TITLE = 若依管理系统 VUE_APP_TITLE = 工程档案资料移交管理系统
# 生产环境配置 # 生产环境配置
ENV = 'production' ENV = 'production'
# 若依管理系统/生产环境 # 工程档案资料移交管理系统/生产环境
VUE_APP_BASE_API = '/prod-api' VUE_APP_BASE_API = '/prod-api'

View File

@ -1,5 +1,5 @@
# 页面标题 # 页面标题
VUE_APP_TITLE = 若依管理系统 VUE_APP_TITLE = 工程档案资料移交管理系统
BABEL_ENV = production BABEL_ENV = production
@ -8,5 +8,5 @@ NODE_ENV = production
# 测试环境配置 # 测试环境配置
ENV = 'staging' ENV = 'staging'
# 若依管理系统/测试环境 # 工程档案资料移交管理系统/测试环境
VUE_APP_BASE_API = '/stage-api' VUE_APP_BASE_API = '/stage-api'

1
.gitignore vendored
View File

@ -1,5 +1,6 @@
.DS_Store .DS_Store
node_modules/ node_modules/
.history/
dist/ dist/
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*

View File

@ -1,8 +1,8 @@
{ {
"name": "ruoyi", "name": "ruoyi",
"version": "3.9.0", "version": "3.9.0",
"description": "若依管理系统", "description": "工程档案资料移交管理系统",
"author": "若依", "author": "bonus",
"license": "MIT", "license": "MIT",
"scripts": { "scripts": {
"dev": "vue-cli-service serve", "dev": "vue-cli-service serve",
@ -39,6 +39,7 @@
"nprogress": "0.2.0", "nprogress": "0.2.0",
"quill": "2.0.2", "quill": "2.0.2",
"screenfull": "5.0.2", "screenfull": "5.0.2",
"sm-crypto": "^0.3.13",
"sortablejs": "1.10.2", "sortablejs": "1.10.2",
"splitpanes": "2.4.1", "splitpanes": "2.4.1",
"vue": "2.6.12", "vue": "2.6.12",

View File

@ -1,5 +1,5 @@
import request from '@/utils/request' import request from '@/utils/request'
import { parseStrEmpty } from "@/utils/ruoyi"; import { parseStrEmpty } from "@/utils/bonus";
// 查询用户列表 // 查询用户列表
export function listUser(query) { export function listUser(query) {

View File

@ -18,7 +18,7 @@ import './assets/icons' // icon
import './permission' // permission control import './permission' // permission control
import { getDicts } from "@/api/system/dict/data" import { getDicts } from "@/api/system/dict/data"
import { getConfigKey } from "@/api/system/config" import { getConfigKey } from "@/api/system/config"
import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree } from "@/utils/ruoyi" import { parseTime, resetForm, addDateRange, selectDictLabel, selectDictLabels, handleTree } from "@/utils/bonus"
// 分页组件 // 分页组件
import Pagination from "@/components/Pagination" import Pagination from "@/components/Pagination"
// 自定义表格工具组件 // 自定义表格工具组件

View File

@ -3,7 +3,7 @@ import {Loading, Message} from 'element-ui'
import { saveAs } from 'file-saver' import { saveAs } from 'file-saver'
import { getToken } from '@/utils/auth' import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode' import errorCode from '@/utils/errorCode'
import { blobValidate } from "@/utils/ruoyi" import { blobValidate } from "@/utils/bonus"
const baseURL = process.env.VUE_APP_BASE_API const baseURL = process.env.VUE_APP_BASE_API
let downloadLoadingInstance let downloadLoadingInstance

23
src/utils/configure.js Normal file
View File

@ -0,0 +1,23 @@
// SM 配置
export const SM_CONFIG = {
SALT: '2cc0c5f9f1749f1632efa9f63e902323', // SM3 盐值16 字节)
SM4_KEY:"78d1295afa99449b99d6f83820e6965c", // SM4 对称加密密钥
SM4_SALT:"f555adf6c01d0ab0761e626a2dae34a2",
SM2_PUBLIC_KEY: 'your-public-key', // SM2 公钥
SM2_PRIVATE_KEY: 'your-private-key' // SM2 私钥
}
// AES 配置
export const AES_CONFIG = {
AES_KEY: 'zhgd@bonus@zhgd@bonus@1234567890', // AES key值
AES_IV: '1234567812345678' // AES 偏移量
}
export function generateUUID() {
// 使用当前时间戳和随机数生成一个 UUID
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
const r = Math.random() * 16 | 0; // 生成随机数
const v = c === 'x' ? r : (r & 0x3 | 0x8); // 根据 UUID 规范生成相应的值
return v.toString(16); // 转换为十六进制
});
}

View File

@ -1,5 +1,5 @@
import Vue from 'vue' import Vue from 'vue'
import { mergeRecursive } from "@/utils/ruoyi" import { mergeRecursive } from "@/utils/bonus"
import DictMeta from './DictMeta' import DictMeta from './DictMeta'
import DictData from './DictData' import DictData from './DictData'

View File

@ -1,4 +1,4 @@
import { mergeRecursive } from "@/utils/ruoyi" import { mergeRecursive } from "@/utils/bonus"
import DictOptions from './DictOptions' import DictOptions from './DictOptions'
/** /**

View File

@ -1,4 +1,4 @@
import { mergeRecursive } from "@/utils/ruoyi" import { mergeRecursive } from "@/utils/bonus"
import dictConverter from './DictConverter' import dictConverter from './DictConverter'
export const options = { export const options = {

View File

@ -1,4 +1,4 @@
import { parseTime } from './ruoyi' import { parseTime } from './bonus'
/** /**
* 表格时间格式化 * 表格时间格式化

View File

@ -3,150 +3,250 @@ import { Notification, MessageBox, Message, Loading } from 'element-ui'
import store from '@/store' import store from '@/store'
import { getToken } from '@/utils/auth' import { getToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode' import errorCode from '@/utils/errorCode'
import { tansParams, blobValidate } from "@/utils/ruoyi" import { tansParams, blobValidate } from '@/utils/bonus'
import cache from '@/plugins/cache' import cache from '@/plugins/cache'
import { saveAs } from 'file-saver' import { saveAs } from 'file-saver'
import { decryptWithSM4, encryptWithSM4, hashWithSM3AndSalt } from '@/utils/sm'
const systemConfig = {
requestConfig: {
encryptRequest: process.env.VUE_APP_ENV === 'production' ? true : true,
checkIntegrity: process.env.VUE_APP_ENV === 'production' ? true : true,
encryptResponse: process.env.VUE_APP_ENV === 'production' ? true : true,
},
}
let downloadLoadingInstance let downloadLoadingInstance
// 是否显示重新登录
export let isRelogin = { show: false } export let isRelogin = { show: false }
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8' axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// 创建axios实例
const service = axios.create({ const service = axios.create({
// axios中请求配置有baseURL选项表示请求URL公共部分 baseURL: process.env.VUE_APP_BASE_API,
baseURL: process.env.VUE_APP_BASE_API, timeout: 30000,
// 超时
timeout: 10000
}) })
// request拦截器 // request 拦截器
service.interceptors.request.use(config => { service.interceptors.request.use(
// 是否需要设置 token (config) => {
const isToken = (config.headers || {}).isToken === false const headers = config.headers || {}
// 是否需要防止数据重复提交 const {
const isRepeatSubmit = (config.headers || {}).repeatSubmit === false isToken = true,
if (getToken() && !isToken) { encryptRequest = true,
config.headers['Authorization'] = 'Bearer ' + getToken() // 让每个请求携带自定义token 请根据实际情况自行修改 checkIntegrity = true,
} encryptResponse = true,
// get请求映射params参数 repeatSubmit = false,
if (config.method === 'get' && config.params) { } = headers
let url = config.url + '?' + tansParams(config.params)
url = url.slice(0, -1)
config.params = {}
config.url = url
}
if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
const requestObj = {
url: config.url,
data: typeof config.data === 'object' ? JSON.stringify(config.data) : config.data,
time: new Date().getTime()
}
const requestSize = Object.keys(JSON.stringify(requestObj)).length // 请求数据大小
const limitSize = 5 * 1024 * 1024 // 限制存放数据5M
if (requestSize >= limitSize) {
console.warn(`[${config.url}]: ` + '请求数据大小超出允许的5M限制无法进行防重复提交验证。')
return config
}
const sessionObj = cache.session.getJSON('sessionObj')
if (sessionObj === undefined || sessionObj === null || sessionObj === '') {
cache.session.setJSON('sessionObj', requestObj)
} else {
const s_url = sessionObj.url // 请求地址
const s_data = sessionObj.data // 请求数据
const s_time = sessionObj.time // 请求时间
const interval = 1000 // 间隔时间(ms),小于此时间视为重复提交
if (s_data === requestObj.data && requestObj.time - s_time < interval && s_url === requestObj.url) {
const message = '数据正在处理,请勿重复提交'
console.warn(`[${s_url}]: ` + message)
return Promise.reject(new Error(message))
} else {
cache.session.setJSON('sessionObj', requestObj)
}
}
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
// 响应拦截器 // 设置请求头
service.interceptors.response.use(res => { config.headers['encryptRequest'] = systemConfig.requestConfig.encryptRequest && encryptRequest ? 'true' : 'false'
// 未设置状态码则默认成功状态 config.headers['checkIntegrity'] = systemConfig.requestConfig.checkIntegrity && checkIntegrity ? 'true' : 'false'
const code = res.data.code || 200 config.headers['encryptResponse'] = systemConfig.requestConfig.encryptResponse && encryptResponse ? 'true' : 'false'
// 获取错误信息
const msg = errorCode[code] || res.data.msg || errorCode['default'] const isRepeatSubmit = repeatSubmit
// 二进制数据则直接返回
if (res.request.responseType === 'blob' || res.request.responseType === 'arraybuffer') { // 处理 Token
return res.data if (getToken() && isToken) {
} config.headers['Authorization'] = 'Bearer ' + getToken()
if (code === 401) { }
if (!isRelogin.show) {
isRelogin.show = true // GET 请求处理 - 统一处理加密逻辑
MessageBox.confirm('登录状态已过期,您可以继续留在该页面,或者重新登录', '系统提示', { confirmButtonText: '重新登录', cancelButtonText: '取消', type: 'warning' }).then(() => { if (config.method === 'get' && config.params) {
isRelogin.show = false // 如果需要加密 GET 请求
store.dispatch('LogOut').then(() => { if (systemConfig.requestConfig.encryptRequest && encryptRequest) {
location.href = '/index' // 将参数转换为查询字符串
}) let paramsString = tansParams(config.params)
}).catch(() => { // 移除末尾的 & 字符
isRelogin.show = false if (paramsString.endsWith('&')) {
}) paramsString = paramsString.slice(0, -1)
} }
return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
} else if (code === 500) { if (paramsString) {
Message({ message: msg, type: 'error' }) // 添加完整性校验哈希
return Promise.reject(new Error(msg)) const hash = hashWithSM3AndSalt(paramsString)
} else if (code === 601) { const encryptedParams = encryptWithSM4(paramsString + '|' + hash)
Message({ message: msg, type: 'warning' })
return Promise.reject('error') // 清空原始 params
} else if (code !== 200) { config.params = {}
Notification.error({ title: msg })
return Promise.reject('error') // 如果 URL 已经有查询参数,需要先清理
} else { let baseUrl = config.url
return res.data const questionMarkIndex = baseUrl.indexOf('?')
} if (questionMarkIndex !== -1) {
}, baseUrl = baseUrl.substring(0, questionMarkIndex)
error => { }
console.log('err' + error)
let { message } = error // 设置加密后的查询参数
if (message == "Network Error") { config.url = baseUrl + '?params=' + encodeURIComponent(encryptedParams)
message = "后端接口连接异常" }
} else if (message.includes("timeout")) { } else {
message = "系统接口请求超时" // 不加密的情况,保持原有逻辑
} else if (message.includes("Request failed with status code")) { let url = config.url + '?' + tansParams(config.params)
message = "系统接口" + message.substr(message.length - 3) + "异常" url = url.slice(0, -1)
} config.params = {}
Message({ message: message, type: 'error', duration: 5 * 1000 }) config.url = url
return Promise.reject(error) }
} }
// POST/PUT 请求处理
if (!isRepeatSubmit && (config.method === 'post' || config.method === 'put')) {
let data = typeof config.data === 'object' ? JSON.stringify(config.data) : config.data
let contentType = config.headers['Content-Type']
if (contentType && contentType.includes('application/json') && typeof data !== 'undefined') {
// 加密数据
if (systemConfig.requestConfig.encryptRequest && encryptRequest) {
config.data = encryptWithSM4(data + '|' + hashWithSM3AndSalt(data))
}
}
// 检查请求数据大小
const requestSize = JSON.stringify({
url: config.url,
data: data,
time: Date.now(),
}).length
const limitSize = 1000 * 1024 * 1024
if (requestSize >= limitSize) {
console.warn(
`[${config.url}]: 请求数据大小超出允许的5MB限制无法进行防重复提交验证。`,
)
return config
}
// 防止重复提交
const sessionObj = cache.session.getJSON('sessionObj') || {}
const requestObj = { url: config.url, data: data, time: Date.now() }
if (
sessionObj.data === requestObj.data &&
requestObj.time - sessionObj.time < 0 &&
sessionObj.url === requestObj.url
) {
console.warn(`[${sessionObj.url}]: 数据正在处理,请勿重复提交`)
return Promise.reject(new Error('数据正在处理,请勿重复提交'))
}
cache.session.setJSON('sessionObj', requestObj)
}
return config
},
(error) => {
console.error(error)
return Promise.reject(error)
},
) )
// 通用下载方法 // 响应拦截器(保持不变)
service.interceptors.response.use(
(res) => {
if (res.headers.encryptresponse && !res.data.hasOwnProperty('code')) {
res.data = JSON.parse(decryptWithSM4(res.data))
}
// 未设置状态码则默认成功状态
const code = res.data.code || 200
// 获取错误信息
const msg = errorCode[code] || res.data.msg || errorCode['default']
// 二进制数据则直接返回
if (
res.request.responseType === 'blob' ||
res.request.responseType === 'arraybuffer'
) {
return res.data
}
if (code === 401) {
if (!isRelogin.show) {
isRelogin.show = true
MessageBox.confirm(
'登录状态已过期,您可以继续留在该页面,或者重新登录',
'系统提示',
{
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning',
},
)
.then(() => {
isRelogin.show = false
store.dispatch('LogOut').then(() => {
location.href =
process.env.VUE_APP_ENV === 'production'
? '/smart-archiving/index'
: '/index'
})
})
.catch(() => {
isRelogin.show = false
})
}
return Promise.reject('无效的会话,或者会话已过期,请重新登录。')
} else if (code === 500) {
Message({ message: msg, type: 'error' })
return Promise.reject(new Error(msg))
} else if (code === 601) {
Message({ message: msg, type: 'warning' })
return Promise.reject('error')
} else if (code !== 200) {
Notification.error({ title: msg })
return Promise.reject('error')
} else {
return res.data
}
},
(error) => {
let { message } = error
if (message == 'Network Error') {
message = '后端接口连接异常'
} else if (message.includes('timeout')) {
message = '系统接口请求超时'
} else if (message.includes('Request failed with status code')) {
message = '系统接口' + message.substr(message.length - 3) + '异常'
}
Message({ message: message, type: 'error', duration: 5 * 1000 })
return Promise.reject(error)
},
)
// 通用下载方法(保持不变)
export function download(url, params, filename, config) { export function download(url, params, filename, config) {
downloadLoadingInstance = Loading.service({ text: "正在下载数据,请稍候", spinner: "el-icon-loading", background: "rgba(0, 0, 0, 0.7)", }) downloadLoadingInstance = Loading.service({
return service.post(url, params, { text: '正在下载数据,请稍候',
transformRequest: [(params) => { return tansParams(params) }], spinner: 'el-icon-loading',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, background: 'rgba(0, 0, 0, 0.7)',
responseType: 'blob', })
...config return service
}).then(async (data) => { .post(url, params, {
const isBlob = blobValidate(data) transformRequest: [
if (isBlob) { (params) => {
const blob = new Blob([data]) return tansParams(params)
saveAs(blob, filename) },
} else { ],
const resText = await data.text() headers: {
const rspObj = JSON.parse(resText) 'Content-Type': 'application/x-www-form-urlencoded',
const errMsg = errorCode[rspObj.code] || rspObj.msg || errorCode['default'] encryptResponse: false,
Message.error(errMsg) },
} responseType: 'blob',
downloadLoadingInstance.close() ...config,
}).catch((r) => { })
console.error(r) .then(async (data) => {
Message.error('下载文件出现错误,请联系管理员!') const isBlob = blobValidate(data)
downloadLoadingInstance.close() if (isBlob) {
}) const blob = new Blob([data])
saveAs(blob, filename)
} else {
const resText = await data.text()
const rspObj = JSON.parse(resText)
const errMsg =
errorCode[rspObj.code] || rspObj.msg || errorCode['default']
Message.error(errMsg)
}
downloadLoadingInstance.close()
})
.catch((r) => {
console.error(r)
Message.error('下载文件出现错误,请联系管理员!')
downloadLoadingInstance.close()
})
} }
export default service export default service

50
src/utils/sm.js Normal file
View File

@ -0,0 +1,50 @@
// src/utils/encryption.js
import { sm2, sm3, sm4 } from 'sm-crypto'
// 配置项例如盐值、SM2 公私钥、SM4 密钥
import { SM_CONFIG } from './configure'
import SM4 from 'sm-crypto/src/sm4'
import { hexToArray } from 'sm-crypto/src/sm2/utils'
// SM3 哈希
export function hashSM3(text) {
// 对数据进行哈希计算
return sm3(text)
}
// 使用 SM3 进行哈希并加入盐值
export function hashWithSM3AndSalt(text) {
// 将文本和盐值拼接在一起
const textWithSalt = SM_CONFIG.SALT + text
// 使用 SM3 进行哈希
return hashSM3(textWithSalt)
}
// SM2 加密
export function encryptWithSM2(text) {
// SM2 公钥加密
return sm2.doEncrypt(text, SM_CONFIG.SM2_PUBLIC_KEY)
}
// SM2 解密
export function decryptWithSM2(encryptedText) {
// SM2 私钥解密
return sm2.doDecrypt(encryptedText, SM_CONFIG.SM2_PRIVATE_KEY)
}
/**
* 加密函数
* @param {string} plainText
* @returns {string} 加密后的密文Hex 编码格式
*/
export function encryptWithSM4(plainText) {
return sm4.encrypt(plainText, SM_CONFIG.SM4_KEY,{ mode: 'cbc', padding: 'pkcs#5',iv:SM_CONFIG.SM4_SALT});
}
/**
* 解密函数
* @param {string} cipherText
* @returns {string} 解密后的明文
*/
export function decryptWithSM4(cipherText){
return SM4.decrypt(cipherText, SM_CONFIG.SM4_KEY,{ mode: 'cbc', padding: 'pkcs#5' ,iv:SM_CONFIG.SM4_SALT});
}

File diff suppressed because it is too large Load Diff

View File

@ -7,7 +7,7 @@ function resolve(dir) {
const CompressionPlugin = require('compression-webpack-plugin') const CompressionPlugin = require('compression-webpack-plugin')
const name = process.env.VUE_APP_TITLE || '若依管理系统' // 网页标题 const name = process.env.VUE_APP_TITLE || '工程档案资料移交管理系统' // 网页标题
const baseUrl = 'http://localhost:8080' // 后端接口 const baseUrl = 'http://localhost:8080' // 后端接口