import Taro from '@tarojs/taro'; import AES from 'crypto-js/aes'; import Utf8 from 'crypto-js/enc-utf8'; const ENCRYPTION_KEY = process.env.TARO_APP_ENCRYPTION_KEY || ''; if (!ENCRYPTION_KEY && process.env.NODE_ENV !== 'production') { console.warn('[secure-storage] TARO_APP_ENCRYPTION_KEY 未设置,敏感数据将以明文存储'); } function encrypt(plaintext: string): string { if (!ENCRYPTION_KEY) { if (process.env.NODE_ENV === 'production') { throw new Error('[secure-storage] TARO_APP_ENCRYPTION_KEY 未设置,生产环境禁止明文存储'); } return plaintext; } return AES.encrypt(plaintext, ENCRYPTION_KEY).toString(); } function decrypt(ciphertext: string): string | null { if (!ENCRYPTION_KEY) { if (process.env.NODE_ENV === 'production') { throw new Error('[secure-storage] TARO_APP_ENCRYPTION_KEY 未设置,生产环境禁止明文读取'); } return ciphertext; } try { const bytes = AES.decrypt(ciphertext, ENCRYPTION_KEY); const result = bytes.toString(Utf8); if (!result) return null; return result; } catch { return null; } } export function secureSet(key: string, value: string): void { const encrypted = encrypt(value); Taro.setStorageSync(key, encrypted); } export function secureGet(key: string): string { const raw = Taro.getStorageSync(key); if (!raw || typeof raw !== 'string') return ''; const result = decrypt(raw); return result ?? ''; } export function secureRemove(key: string): void { Taro.removeStorageSync(key); }