( compressedData: string )
| 13 | * - key: base64url-encoded 256-bit key for the URL fragment |
| 14 | */ |
| 15 | export async function encrypt( |
| 16 | compressedData: string |
| 17 | ): Promise<{ ciphertext: string; key: string }> { |
| 18 | const cryptoKey = await crypto.subtle.generateKey( |
| 19 | { name: 'AES-GCM', length: 256 }, |
| 20 | true, |
| 21 | ['encrypt'] |
| 22 | ); |
| 23 | |
| 24 | const iv = crypto.getRandomValues(new Uint8Array(12)); |
| 25 | const plaintext = new TextEncoder().encode(compressedData); |
| 26 | |
| 27 | const encrypted = await crypto.subtle.encrypt( |
| 28 | { name: 'AES-GCM', iv }, |
| 29 | cryptoKey, |
| 30 | plaintext |
| 31 | ); |
| 32 | |
| 33 | // Prepend IV to ciphertext (IV || ciphertext+tag) |
| 34 | const combined = new Uint8Array(iv.length + encrypted.byteLength); |
| 35 | combined.set(iv, 0); |
| 36 | combined.set(new Uint8Array(encrypted), iv.length); |
| 37 | |
| 38 | const rawKey = await crypto.subtle.exportKey('raw', cryptoKey); |
| 39 | |
| 40 | return { |
| 41 | ciphertext: bytesToBase64url(combined), |
| 42 | key: bytesToBase64url(new Uint8Array(rawKey)), |
| 43 | }; |
| 44 | } |
| 45 | |
| 46 | /** |
| 47 | * Decrypt a ciphertext string using a base64url-encoded AES-256-GCM key. |
no test coverage detected