feat(projects): 添加cryptojs,对本地缓存数据进行加密

This commit is contained in:
Soybean
2022-01-01 22:52:05 +08:00
parent 25d3404c9c
commit 7a0648dba5
5 changed files with 994 additions and 775 deletions

27
src/utils/crypto/index.ts Normal file
View File

@ -0,0 +1,27 @@
import CryptoJS from 'crypto-js';
const CryptoSecret = '__CryptoJS_Secret__';
/**
* 加密数据
* @param data - 数据
* @param secret - 密钥
*/
export function encrypto(data: any) {
const newData = JSON.stringify(data);
return CryptoJS.AES.encrypt(newData, CryptoSecret).toString();
}
/**
* 解密数据
* @param ciphertext - 密文
* @param secret - 密钥
*/
export function decrypto(ciphertext: string) {
const bytes = CryptoJS.AES.decrypt(ciphertext, CryptoSecret);
const originalText = bytes.toString(CryptoJS.enc.Utf8);
if (originalText) {
return JSON.parse(originalText);
}
return null;
}

View File

@ -1,21 +1,37 @@
import { encrypto, decrypto } from '../crypto';
interface StorageData {
value: unknown;
expire: number | null;
}
/** 默认缓存期限为7天 */
const DEFAULT_CACHE_TIME = 60 * 60 * 24 * 7;
export function setLocal(key: string, value: unknown, expire: number | null = DEFAULT_CACHE_TIME) {
const json = JSON.stringify({ value, expire: expire !== null ? new Date().getTime() + expire * 1000 : null });
const storageData: StorageData = { value, expire: expire !== null ? new Date().getTime() + expire * 1000 : null };
const json = encrypto(storageData);
window.localStorage.setItem(key, json);
}
export function getLocal<T>(key: string) {
const json = window.localStorage.getItem(key);
if (json) {
const data = JSON.parse(json);
const { value, expire } = data;
/** 在有效期内直接返回 */
if (expire === null || expire >= Date.now()) {
return value as T;
let storageData: StorageData | null = null;
try {
storageData = decrypto(json);
} catch {
// 防止解析失败
}
if (storageData) {
const { value, expire } = storageData;
// 在有效期内直接返回
if (expire === null || expire >= Date.now()) {
return value as T;
}
}
removeLocal(key);
return null;
}
return null;
}

View File

@ -1,14 +1,21 @@
import { encrypto, decrypto } from '../crypto';
export function setSession(key: string, value: unknown) {
const json = JSON.stringify(value);
const json = encrypto(value);
sessionStorage.setItem(key, json);
}
export function getSession<T>(key: string) {
const json = sessionStorage.getItem(key);
let data: T | null = null;
if (json) {
return JSON.parse(json) as T;
try {
data = decrypto(json);
} catch {
// 防止解析失败
}
}
return null;
return data;
}
export function removeSession(key: string) {