( data: unknown, dataKey: Uint8Array, )
| 138 | } |
| 139 | |
| 140 | export async function encryptWithDataKey( |
| 141 | data: unknown, |
| 142 | dataKey: Uint8Array, |
| 143 | ): Promise<Uint8Array> { |
| 144 | const nonce = getRandomBytes(12); |
| 145 | const key = await getAesKey(dataKey); |
| 146 | const plaintext = new TextEncoder().encode(JSON.stringify(data)); |
| 147 | const encrypted = await crypto.subtle.encrypt( |
| 148 | { name: 'AES-GCM', iv: toArrayBuffer(nonce) }, |
| 149 | key, |
| 150 | plaintext, |
| 151 | ); |
| 152 | // SubtleCrypto appends authTag to the ciphertext |
| 153 | const encryptedBytes = new Uint8Array(encrypted); |
| 154 | |
| 155 | // Bundle: version(1) + nonce(12) + ciphertext+authTag |
| 156 | const bundle = new Uint8Array(1 + 12 + encryptedBytes.length); |
| 157 | bundle[0] = 0; // version |
| 158 | bundle.set(nonce, 1); |
| 159 | bundle.set(encryptedBytes, 13); |
| 160 | return bundle; |
| 161 | } |
| 162 | |
| 163 | export async function decryptWithDataKey( |
| 164 | bundle: Uint8Array, |
no test coverage detected