sm2-加密

This commit is contained in:
wu.jifen
2025-08-24 14:32:39 +08:00
parent de5c3e2f46
commit 8b3a60f22d
2 changed files with 22 additions and 12 deletions

View File

@@ -3,7 +3,6 @@ import { Loading, Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken, removeToken } from '@/assets/js/utils/auth'
import router from '@/router'
import { sm2 } from 'sm-crypto'
import { logger } from 'runjs/lib/common'
import {
@@ -49,19 +48,30 @@ service.interceptors.request.use(
if (deviceId) {
config.headers['deviceId'] = localStorage.getItem('deviceId')
}
// 3. 判断是否需要加密:跳过非 JSON 请求、OPTIONS 请求、自定义排除项
const shouldSkipEncryption = () => {
// 跳过 Content-Type 不是 application/json 的请求
const contentType =
config.headers['Content-Type'] || config.headers['content-type']
if (contentType && !contentType.includes('application/json')) {
return true
}
// 加密处理
if (shouldEncrypt(config)) {
// 添加加密标识l, 方便自测
// 跳过自定义标记不加密的请求
return !shouldEncrypt(config)
}
// 4. 执行加密逻辑
if (!shouldSkipEncryption() && shouldEncrypt(config)) {
// 添加加密标识(便于调试)
config.headers['X-Encrypted'] = 'true'
if (config.data) {
// 保存原始数据用于调试
config.originalData = config.data
// config.data = encryptData(config.data)
var requestJson = { content: encrypt(config.data, config.url) }
config.data = JSON.stringify(requestJson)
config.headers['Content-Type'] = 'application/json'
// 加密数据,包装成 { content: "encryptedString" }
config.data = { content: encrypt(config.data, config.url) }
}
}
@@ -79,7 +89,7 @@ service.interceptors.request.use(
service.interceptors.response.use(
response => {
let res = response.data
// 解密处理
// 解密处理 todo 用config.headers['X-Encrypted'] === 'true'判断是否需要解密不一定准确
if (response.config.headers['X-Encrypted'] === 'true') {
try {
res = decryptWithPrivateKey(res, privateKeyHex, 1)