Vue 项目中 使用 CryptoJS 对请求后端接口获得的数据实现前端加密解密

用到了axios 和 CryptoJS, 基本的安装啥的就不废话了

直接上封装的代码:

import CryptoJS from 'crypto-js/crypto-js'
import axios from 'axios';
const CancelToken = axios.CancelToken
// ****************************  加密代码 *******************************
function DecryptData(data) {
	try {
		var sp = splitData(data);
		if (!sp) return data;
		var decrypt = CryptoJS.AES.decrypt(sp.data, CryptoJS.enc.Latin1.parse(sp.key), {
			mode: CryptoJS.mode.ECB,
			padding: CryptoJS.pad.Pkcs7
		});
		var tt = CryptoJS.enc.Utf8.stringify(decrypt).toString();
		return JSON.parse(tt);
	} catch (err) {
		return data;
	}
}

function splitData(str) {
	var offset = parseInt(str.substr(3, 2));
	var length = parseInt(str.substr(offset + 2, 2));
	return {
		key: str.substr(offset + 4, length),
		data: str.substr(0, 3) + str.substr(5, offset - 3) + str.substr(offset + 4 + length)
	}
}

function randomWord(randomFlag, min, max) {
	var str = "",
		range = min,
		arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l',
			'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I',
			'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
		];

	// 随机产生
	if (randomFlag) {
		range = Math.round(Math.random() * (max - min)) + min;
	}
	var pos = 0;
	for (var i = 0; i < range; i++) {
		pos = Math.round(Math.random() * (arr.length - 1));
		str += arr[pos];
	}
	return str;
}

function genKey() {
	return randomWord(false, 16);
}

function EncryptData(data) {
	var key = genKey();
	var srcs = CryptoJS.enc.Utf8.parse(data);
	var encrypted = CryptoJS.AES.encrypt(srcs, CryptoJS.enc.Latin1.parse(key), {
		mode: CryptoJS.mode.ECB,
		padding: CryptoJS.pad.Pkcs7
	});
	return combineEncrypt(key, encrypted.toString());
}

function randomoffset(length) {
	return 16;
}

function combineEncrypt(key, encrypted) {
	var offset = randomoffset(encrypted.length);

	return encrypted.substr(0, 3) + offset +
		encrypted.substr(3, offset - 3) + key.length + key +
		encrypted.substr(offset);
}

function decryptInterceptorHandle(response) {
	//解密
	if (typeof(response.data) == "string") {
		response.data = DecryptData(response.data);
	}
	return response;
}

function encryptInterceptorHandle(config) {
	// 对所有POST put delete get请加密,必须是json数据提交,不支持表单
	if (config && config.data) {
		if (config.method == "post" || config.method == "put" || config.method == "delete" || config.method == "get") {
			var encrypted = EncryptData(JSON.stringify(config.data))
			config.data = encrypted;
		}
	}
	return config;
}
// ****************************  加密代码 *******************************
var cancel_ = false;
export default {
	install(Vue) {
		let GLOBAL = Vue.prototype.GLOBAL;
		GLOBAL.api = {

		};
		GLOBAL.ajax = {
			requestInterceptors: [
				(config) => {
					if (GLOBAL.ajax.options.isDebug() && GLOBAL.ajax.options.Authorization)
						config.headers.common["Authorization"] = GLOBAL.ajax.options.Authorization;
					config.headers.common['Content-Type'] = 'application/json';
					return config;
				}
			],
			responseInterceptors: [],
			responseErrorsInterceptors:[],
			options: {
				isDebug: () => {
					return !(window.location.host.indexOf(GLOBAL.ajax.options.localKey ? GLOBAL.ajax.options.localKey : "localhost") ==
						-1);
				},
			},
			debug: {
				enable: (options) => {
					if (options.localKey)
						GLOBAL.ajax.options.localKey = options.localKey;
					if (options.Authorization)
						GLOBAL.ajax.options.Authorization = options.Authorization;
				}
			},
			encrypt: {
				enable: (enable) => {
					GLOBAL.ajax.options.encrypt = enable;
				}
			},
			pushRequestInterceptors(it) {
				//待校验,必须有参数
				GLOBAL.ajax.requestInterceptors.push(it);
			},
			pushResponseInterceptors(it) {
				//待校验,必须有参数
				GLOBAL.ajax.responseInterceptors.push(it);
			},
			pushResponseErrorsInterceptors(it) {
				//待校验,必须有参数
				GLOBAL.ajax.responseErrorsInterceptors.push(it);
			},
			createApi(serviceName, baseURL) {
				let apiName = "$" + serviceName;
				if (GLOBAL.api[apiName]) {
					return GLOBAL.api[apiName];
				}

				let tempService = axios.create({
					baseURL: GLOBAL.ajax.options.isDebug() ? baseURL.dev : baseURL.prod
				});
				tempService.interceptors.response.use((res) => {
					GLOBAL.ajax.responseInterceptors.forEach(it => {
						res = it(res);
					})
					//解密方法;
					if (!GLOBAL.ajax.options.encrypt) return res;
					return decryptInterceptorHandle(res);
				}, (error) => {
					GLOBAL.ajax.responseErrorsInterceptors.forEach(it => {
						error = it(error);
					})

					return error;
				})
				tempService.interceptors.request.use((config) => {
					GLOBAL.ajax.requestInterceptors.forEach(it => {
						config = it(config);
					})
					//加密方法;
					if (!GLOBAL.ajax.options.encrypt) return config;
					return encryptInterceptorHandle(config);
				}, (error) => {
					return error;
				});
				GLOBAL.api[apiName] = tempService;
				return tempService;
			},
		}
	}
};

 

你可能感兴趣的:(记录,vue)