// crypto:AES-GCM 加解密工具(Web Crypto API) /** 從 hex 字串匯入 AES-GCM key */ async function importKey(hexKey: string): Promise { const raw = new Uint8Array(hexKey.match(/.{1,2}/g)!.map(b => parseInt(b, 16))); return crypto.subtle.importKey('raw', raw, { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']); } /** 加密 plaintext,回傳 { encrypted, iv }(均為 base64) */ export async function encrypt(plaintext: string, hexKey: string): Promise<{ encrypted: string; iv: string }> { const key = await importKey(hexKey); const iv = crypto.getRandomValues(new Uint8Array(12)); const encoded = new TextEncoder().encode(plaintext); const cipherBuf = await crypto.subtle.encrypt({ name: 'AES-GCM', iv }, key, encoded); return { encrypted: btoa(String.fromCharCode(...new Uint8Array(cipherBuf))), iv: btoa(String.fromCharCode(...iv)), }; } /** 解密,回傳 plaintext */ export async function decrypt(encrypted: string, iv: string, hexKey: string): Promise { const key = await importKey(hexKey); const ivBuf = Uint8Array.from(atob(iv), c => c.charCodeAt(0)); const cipherBuf = Uint8Array.from(atob(encrypted), c => c.charCodeAt(0)); const plainBuf = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ivBuf }, key, cipherBuf); return new TextDecoder().decode(plainBuf); }