1.使用crypto-js来加密和解密。
npm i --save-dev crypto-js
import CryptoJS from 'crypto-js';
2.对 crypto-js 设置密钥和密钥偏移量,可以采用将一个私钥经 MD5 加密生成16位密钥获得。
const SECRET_KEY = CryptoJS.enc.Utf8.parse('3333e6e143439161');
const SECRET_IV = CryptoJS.enc.Utf8.parse('e3bbe7e3ba84431a');
3.加密功能
const encrypt = (data: object | string): string => {
if (typeof data === 'object') {
try {
data = JSON.stringify(data);
} catch (e) {
throw new Error('encrypt error' + e);
}
}
const dataHex = CryptoJS.enc.Utf8.parse(data);
const encrypted = CryptoJS.AES.encrypt(dataHex, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
return encrypted.ciphertext.toString();
};
4.解密功能
const decrypt = (data: string) => {
const encryptedHexStr = CryptoJS.enc.Hex.parse(data);
const str = CryptoJS.enc.Base64.stringify(encryptedHexStr);
const decrypt = CryptoJS.AES.decrypt(str, SECRET_KEY, {
iv: SECRET_IV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
});
const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
};
storage API功能的实现
const setStorage = (key: string, value: any, expire: number = 24 * 60): boolean => {
if (value === '' || value === null || value === undefined) {
value = null;
}
if (isNaN(expire) || expire < 0) {
throw new Error('Expire must be a number');
}
const data = {
value,
time: Date.now(),
expire: Date.now() + 1000 * 60 * expire,
};
window[config.type].setItem(
autoAddPreFix(key),
config.isEncrypt ? encrypt(JSON.stringify(data)) : JSON.stringify(data),
);
return true;
};
const getStorageFromKey = (key: string) => {
if (config.prefix) {
key = autoAddPreFix(key);
}
if (!window[config.type].getItem(key)) {
return null;
}
const storageVal = config.isEncrypt
? JSON.parse(decrypt(window[config.type].getItem(key) as string))
: JSON.parse(window[config.type].getItem(key) as string);
const now = Date.now();
if (now >= storageVal.expire) {
removeStorageFromKey(key);
return null;
} else {
return storageVal.value;
}
};
const getAllStorage = () => {
const storageList: any = {};
const keys = Object.keys(window[config.type]);
keys.forEach((key) => {
const value = getStorageFromKey(key);
if (value !== null) {
storageList[key] = value;
}
});
return storageList;
};
const getStorageLength = () => {
return window[config.type].length;
};
const removeStorageFromKey = (key: string) => {
if (config.prefix) {
key = autoAddPreFix(key);
}
window[config.type].removeItem(key);
};
const clearStorage = () => {
window[config.type].clear();
};
const autoAddPreFix = (key: string) => {
const prefix = config.prefix || '';
return `${prefix}_${key}`;
};
在使用时导入即可
import {
setStorage
} from './util/storage'
setStorage('name', 'ashin', 1)