用到的插件
pnpm add crypto-js
pnpm add -D @types/crypto-js
一、Unicode编码
export const zhToUnicode = (str) => {
const txt = escape(str).toLocaleLowerCase().replace(/%u/gi, '\\u');
return txt
.replace(/%7b/gi, '{')
.replace(/%7d/gi, '}')
.replace(/%3a/gi, ':')
.replace(/%2c/gi, ',')
.replace(/%27/gi, "'")
.replace(/%22/gi, '"')
.replace(/%5b/gi, '[')
.replace(/%5d/gi, ']')
.replace(/%3D/gi, '=')
.replace(/%20/gi, ' ')
.replace(/%3E/gi, '>')
.replace(/%3C/gi, '<')
.replace(/%3F/gi, '?');
};
二、Unicode解码
export const unincodeToZh = (str) => unescape(str.replace(/\\u/gi, '%u'));
三、Utf8编码
export const zhToUtf8 = (str) =>
str.replace(/[^\u0000-\u00FF]/g, function ($0) {
return escape($0).replace(/(%u)(\w{4})/gi, '&#x$2;');
});
四、Utf8解码
export const utf8ToZh = (str) => unescape(str.replace(/&#x/g, '%u').replace(/;/g, ''));
五、Base64编码
export const base64Encode = (str) => CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(str));
六、Base64解码
export const base64Decode = (str) => CryptoJS.enc.Base64.parse(str).toString(CryptoJS.enc.Utf8);
七、URL编码
// encodeURI不会对特殊字符编码,而encodeURIComponent会对特殊字符编码。
export const urlEncode = (str) => /* encodeURI(str) */ encodeURIComponent(str);
八、URL解码
export const urlDecode = (str) => decodeURIComponent(str);
九、MD5加密
export const getMD5Str = (str) => CryptoJS.MD5(str).toString();
十、SHA256加密
export const getSHA256Str = (str) => CryptoJS.SHA256(str).toString();
十一、AES加密
export const AESEncrypt = (str, pwd) => CryptoJS.AES.encrypt(str, pwd).toString();
十二、AES解密
export const AESDecrypt = (str, pwd) => CryptoJS.AES.decrypt(str, pwd).toString(CryptoJS.enc.Utf8);
十三、DES加密
export const DESEncrypt = (str, pwd) => CryptoJS.DES.encrypt(str, pwd).toString();
十四、DES解密
export const DESDecrypt = (str, pwd) => CryptoJS.DES.decrypt(str, pwd).toString(CryptoJS.enc.Utf8);