| 32 | * Encrypt an `Item` into an `EncryptedItem`. |
| 33 | */ |
| 34 | async function encrypt(item: Item): Promise<EncryptedItem> { |
| 35 | const { id, title } = item |
| 36 | |
| 37 | const enc = new TextEncoder() |
| 38 | const encoded = enc.encode(title) |
| 39 | const iv = crypto.getRandomValues(new Uint8Array(12)) |
| 40 | |
| 41 | const encrypted = await crypto.subtle.encrypt( |
| 42 | { |
| 43 | iv: iv as BufferSource, |
| 44 | name: `AES-GCM`, |
| 45 | }, |
| 46 | key, |
| 47 | encoded as BufferSource |
| 48 | ) |
| 49 | |
| 50 | const ciphertext = base64.fromByteArray(new Uint8Array(encrypted)) |
| 51 | const iv_str = base64.fromByteArray(iv) |
| 52 | |
| 53 | return { |
| 54 | id, |
| 55 | ciphertext, |
| 56 | iv: iv_str, |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /* |
| 61 | * Decrypt an `EncryptedItem` to an `Item`. |