import CryptoJS from 'crypto-js' const DEFAULT_KEY_LENGTH = 16 const _k = import.meta.env.VITE_CRYPTO_KEY const _iv = import.meta.env.VITE_CRYPTO_IV const key = CryptoJS.enc.Utf8.parse( _k.length === DEFAULT_KEY_LENGTH ? _k : window.decodeURIComponent(window.atob(_k)), ) const iv = CryptoJS.enc.Utf8.parse( _iv.length === DEFAULT_KEY_LENGTH ? _iv : window.decodeURIComponent(window.atob(_iv)), ) /** * 使用登录接口约定的 AES-CBC/PKCS7 规则解密内容。 * tk、tiv 不传时分别使用 VITE_CRYPTO_KEY、VITE_CRYPTO_IV。 */ export function decrypt(word: string, tk?: string, tiv?: string): string { const realKey = tk && tk.length === DEFAULT_KEY_LENGTH ? CryptoJS.enc.Utf8.parse(tk) : key const realIv = tiv && tiv.length === DEFAULT_KEY_LENGTH ? CryptoJS.enc.Utf8.parse(tiv) : iv const decrypted = CryptoJS.AES.decrypt(word, realKey, { iv: realIv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, }) const decryptedText = decrypted.toString(CryptoJS.enc.Utf8) const timestampLength = String(Date.now()).length return decryptedText.slice(0, decryptedText.length - timestampLength) } /** * 使用登录接口约定的 AES-CBC/PKCS7 规则加密密码。 * tk、tiv 不传时分别使用 VITE_CRYPTO_KEY、VITE_CRYPTO_IV。 */ export function encrypt(word: string, tk?: string, tiv?: string): string { const realKey = tk && tk.length === DEFAULT_KEY_LENGTH ? CryptoJS.enc.Utf8.parse(tk) : key const realIv = tiv && tiv.length === DEFAULT_KEY_LENGTH ? CryptoJS.enc.Utf8.parse(tiv) : iv const source = CryptoJS.enc.Utf8.parse(`${word}${Date.now()}`) const encrypted = CryptoJS.AES.encrypt(source, realKey, { iv: realIv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7, }) return encrypted.toString() }