(data: any, dataKey: Uint8Array)
| 95 | * Encrypt data using AES-256-GCM with the data encryption key |
| 96 | */ |
| 97 | export function encryptWithDataKey(data: any, dataKey: Uint8Array): Uint8Array { |
| 98 | const nonce = getRandomBytes(12); |
| 99 | const cipher = createCipheriv('aes-256-gcm', dataKey, nonce); |
| 100 | |
| 101 | const plaintext = new TextEncoder().encode(JSON.stringify(data)); |
| 102 | const encrypted = Buffer.concat([ |
| 103 | cipher.update(plaintext), |
| 104 | cipher.final() |
| 105 | ]); |
| 106 | |
| 107 | const authTag = cipher.getAuthTag(); |
| 108 | |
| 109 | // Bundle: version(1) + nonce (12) + ciphertext + auth tag (16) |
| 110 | const bundle = new Uint8Array(12 + encrypted.length + 16 + 1); |
| 111 | bundle.set([0], 0); |
| 112 | bundle.set(nonce, 1); |
| 113 | bundle.set(new Uint8Array(encrypted), 13); |
| 114 | bundle.set(new Uint8Array(authTag), 13 + encrypted.length); |
| 115 | |
| 116 | return bundle; |
| 117 | } |
| 118 | |
| 119 | /** |
| 120 | * Decrypt data using AES-256-GCM with the data encryption key |
no test coverage detected