hjh-encrypt
v1.0.3
Published
前端加解密
Downloads
3
Readme
介绍 📖
前端加解密工具包,非对称和对称加密,全局对post请求data ,json格式加密
安装使用步骤 📔
pnpm hjh-encrypt
- 加密开关
1.axios 拦截器拦截和请求加密
import { CryptoHelper, cryptoSingleton } from "hjh-encrypt";
展示加解密核心代码如下:(全局配置参数加密和是否数字签名)
export interface CustomAxiosRequestConfig extends InternalAxiosRequestConfig {
signature?: boolean;
encrypt?: boolean;
}
1. 请求加密:
this.service.interceptors.request.use(
(config: CustomAxiosRequestConfig) => {
const userStore = useUserStore();
if (config.method?.toLowerCase() === "post" && config.data && config.encrypt) {
const { cipherText, combinedKeyIv } = CryptoHelper.sm4DoEncrypt(JSON.stringify(config.data));
config.headers["x-crypto-key"] = combinedKeyIv;
config.data = { cipherText };
if (config.signature) {//判断是否有数据签名,数据签名需要token参数
const token = userStore.token;
const signParams = CryptoHelper.signature(cipherText, token);
Object.assign(config.headers, signParams);
}
}
//头部携带参数前后端商量名称
if (config.headers && typeof config.headers.set === "function") {
config.headers.set("X-Auth-Token", userStore.token);
config.headers.set("cryptoToken", cryptoSingleton.getCryptoToken());
}
return config;
},
(error: AxiosError) => {
return Promise.reject(error);
}
);
2.响应解密
this.service.interceptors.response.use(
(response: AxiosResponse) => {
const { data } = response;
const userStore = useUserStore();
//token 拿的是headers["x-auth-token"]
const token = response.headers["x-auth-token"];
//解密响应数据
if (response.headers["x-crypto-key"]) {
const newKeyIv = CryptoHelper.sm2DoDecrypt(response.headers["x-crypto-key"]);
const res = CryptoHelper.sm4DoDecrypt(data, newKeyIv);
if (res.code !== ResultEnum.SUCCESS) {
ElMessage.error(res.msg);
return Promise.reject(res);
} else {
console.log(res);
return res;
}
} else {
return data;
}
},
async (error: AxiosError) => {
return Promise.reject(error);
}
);
2.前端基础调用配置
步骤一:获取公私钥绑定
方式1:
routers 的beforeEach 下拦截 开启(**注意前提是判断跳转到登录页后**)
import { cryptoSingleton } from "hjh-encrypt";
cryptoSingleton.resetInitialization();
cryptoSingleton.init(传入http实例参数,url);
举例:cryptoSingleton.init(http, "/auth/encrypt/getPublicKey"");
方式2: 直接在登录页登陆之前调用
步骤二:获取公私钥绑定
登录成功后开启会话绑定
cryptoSingleton.newSm4(传入http实例参数,url);