vue3封裝AES(CryptoJS)前端加密解密通信代碼實現(xiàn)
項目場景:
防止數(shù)據(jù)被爬取,前后端傳參接收參數(shù)需要加密處理,使用AES加密。主要使用CryptoJS庫中的函數(shù)方法,加密:CryptoJS.AES.encrypt(), 解密:CryptoJS.AES.decrypt()。
代碼實現(xiàn)
- 安裝CryptoJS庫:
npm install crypto-js
- 創(chuàng)建文件夾,@/utils/secret,引入CryptoJS庫并封裝加密解密函數(shù)方法:
import CryptoJS from 'crypto-js/crypto-js'; const key = CryptoJS.enc.Utf8.parse('123321'); // 密鑰 后端提供 const iv = CryptoJS.enc.Utf8.parse(''); // 偏移量 /** * AES加密 :字符串 key iv 返回base64 */ export function Encrypt(word) { const srcs = CryptoJS.enc.Utf8.parse(word); const encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, }); return CryptoJS.enc.Base64.stringify(encrypted.ciphertext); } /** * AES 解密 :字符串 key iv 返回base64 * */ export function Decrypt(word) { const base64 = CryptoJS.enc.Base64.parse(word); const src = CryptoJS.enc.Base64.stringify(base64); const decrypt = CryptoJS.AES.decrypt(src, key, { iv: iv, mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7, }); return CryptoJS.enc.Utf8.stringify(decrypt); }
- 引入加密解密方法,對axios中封裝的request 請求前的統(tǒng)一處理做加密:
// 引入 import { Encrypt, Decrypt } from '/@/utils/secret'; this.axiosInstance.interceptors.request.use((config: AxiosRequestConfig) => { // If cancel repeat request is turned on, then cancel repeat request is prohibited // @ts-ignore const { ignoreCancelToken } = config.requestOptions; const ignoreCancel = ignoreCancelToken !== undefined ? ignoreCancelToken : this.options.requestOptions?.ignoreCancelToken; !ignoreCancel && axiosCanceler.addPending(config); if (requestInterceptors && isFunction(requestInterceptors)) { config = requestInterceptors(config, this.options); } // 關(guān)鍵代碼: // JSON加密,formData不加密(對需要處理的數(shù)據(jù)格式做判斷) if (Object.prototype.toString.call(config.data) != '[object FormData]') { config.data = { encryptedData: Encrypt(JSON.stringify(config.data)) }; // 加密傳參,后端要求的傳參:encryptedData:加密參數(shù) } return config; }, undefined);
- response 響應(yīng)前的統(tǒng)一處理做解密:
this.axiosInstance.interceptors.response.use(async (res: AxiosResponse<any>) => { // 關(guān)鍵代碼: // 導(dǎo)出時數(shù)據(jù)格式為blob不解密(對需要處理的數(shù)據(jù)格式做判斷) if (Object.prototype.toString.call(res.data) != '[object Blob]') { res.data = JSON.parse(Decrypt(res.data)); // 解密返回參數(shù) } const config = res.config; if (res.data.code === 401) { // 如果未認(rèn)證,并且未進(jìn)行刷新令牌,說明可能是訪問令牌過期了 if (!isRefreshToken) { isRefreshToken = true; // 1. 獲取到刷新token if (getRefreshToken()) { // 2. 進(jìn)行刷新訪問令牌 try { const refreshTokenRes = await this.refreshToken(); // 2.1 刷新成功,則回放隊列的請求 + 當(dāng)前請求 setToken('Bearer ' + refreshTokenRes.data.data.accessToken); (config as Recordable).headers.Authorization = getToken(); requestList.forEach((cb: any) => { cb(); }); requestList = []; return new Promise((resolve) => { resolve(this.axiosInstance(config)); }); // res = await Promise.all([this.axiosInstance(config)])[0] } catch (e) { requestList.forEach((cb: any) => { cb(); }); } finally { requestList = []; isRefreshToken = false; } } } else { // 添加到隊列,等待刷新獲取到新的令牌 return new Promise((resolve) => { requestList.push(() => { (config as Recordable).headers.Authorization = getToken(); // 讓每個請求攜帶自定義token 請根據(jù)實際情況自行修改 resolve(this.axiosInstance(config)); }); }); } } res && axiosCanceler.removePending(res.config); if (responseInterceptors && isFunction(responseInterceptors)) { res = responseInterceptors(res); } return res; }, undefined);
最終效果
加密傳參:
后端返回參數(shù)加密:
在線加密解密工具:https://www.mklab.cn/utils/aes 或者 http://tools.jb51.net/password/aes_encode
總結(jié)
到此這篇關(guān)于vue3封裝AES(CryptoJS)前端加密解密通信代碼實現(xiàn)的文章就介紹到這了,更多相關(guān)vue3封裝AES加密解密通信內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue3編譯報錯ESLint:defineProps is not defined&nbs
這篇文章主要介紹了vue3編譯報錯ESLint:defineProps is not defined no-undef的問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03Vue3中的element-plus表格實現(xiàn)代碼
這篇文章主要介紹了Vue3中的element-plus表格實現(xiàn)代碼,用組件屬性實現(xiàn)跳轉(zhuǎn)路由,本文通過實例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2024-05-05淺談vue在html中出現(xiàn){{}}的原因及解決方式
這篇文章主要介紹了淺談vue在html中出現(xiàn){{}}的原因及解決方式,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-11-11vue2從數(shù)據(jù)變化到視圖變化之diff算法圖文詳解
這篇文章主要介紹了vue2從數(shù)據(jù)變化到視圖變化之diff算法圖文詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Vue使用Print.js打印div方式(選中區(qū)域的html)
這篇文章主要介紹了Vue使用Print.js打印div方式(選中區(qū)域的html),具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03