import * as CryptoJS from 'crypto-js' import { Base64 } from 'js-base64' let realKey = CryptoJS.SHA1( CryptoJS.SHA1('infoaeskey123456')).toString().substring(0, 32) let key = CryptoJS.enc.Hex.parse(realKey) const prefix = 'a$' const suffix = '~' // aes加密 const encrypt = function (word: string | boolean): string | boolean { if (typeof word === 'boolean') { return word } // 如果以a$ 或者AES开头的数据不用再次加密 if ((word.startsWith(prefix) && word.endsWith(suffix)) || word === '') { return word } else { let srcs = CryptoJS.enc.Utf8.parse(word) let encrypted = CryptoJS.AES.encrypt(srcs, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }) return `${prefix}${encrypted.ciphertext.toString()}${suffix}` } } // aes解密 const decrypt = function (word: string): string { // 判断是否是 AES 加密的 if (!word.startsWith(prefix)) { throw new Error('不是AES加密的字符串') } word = word.substring(prefix.length, word.length - suffix.length) word = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(word)) // 16转base64 let decrypt = CryptoJS.AES.decrypt(word, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }) return CryptoJS.enc.Utf8.stringify(decrypt).toString() } const addBase64 = function (word: string, uri?: boolean): string { if (word.startsWith('b$') || word === '') { return word } if (uri) { return `b$${Base64.encodeURI(word)}~` } else { return `b$${Base64.encode(word)}~` } } // 添加 base64 解密函数 const decodeBase64 = function (word: string): string { if (!word || typeof word !== 'string') { return word } // 检查是否是 base64 编码的字符串 if (!word.startsWith('b$') || !word.endsWith('~')) { return word } // 移除前缀和后缀 word = word.substring(2, word.length - 1) try { // 尝试 URI 解码 return Base64.decode(word) } catch (e) { console.warn('Base64 decode failed:', e) return word } } const isBase64 = function (val: string): boolean { if (val.indexOf('b$') >= 0) { return true } else { return false } } export { encrypt, decrypt, isBase64, addBase64, decodeBase64 }