JS 可逆加密的一种实现

/* 
 * 利用String对象的charCodeAt()方法和fromCharCode()方法对可用JSON.parse进行序列化的数据进行加密的数据加密解密
 * Author: zhangji
 * Create: 2019.10.22
 **/

const Crypto = {
	//加密
	encryption(data) {
		data = JSON.stringify(data)
		let str = '';
		let alterText = [];
		let varCost = [];
		const TextLength = data.length;
		for (let i = 0; i < TextLength; i++) {
			let random = parseInt(Math.random() * 266);
			alterText[i] = data.charCodeAt(i) + random;
			varCost[i] = random;
		}
		for (let i = 0; i < TextLength; i++) {
			str += String.fromCharCode(alterText[i], varCost[i]);
		}
		return str;
	},

	//解密
	decrypt(text) {
		let str = '';
		let alterText = [];
		let varCost = [];
		const TextLength = text.length;
		for (let i = 0; i < TextLength; i++) {
			alterText[i] = text.charCodeAt(i);
			varCost[i] = text.charCodeAt(i + 1);
		}
		for (let i = 0; i < TextLength; i = i + 2) {
			str += String.fromCharCode(alterText[i] - varCost[i]);
		}
		return JSON.parse(str);
	}
};
export default Crypto;
原文地址:https://www.cnblogs.com/YooHoeh/p/12098869.html