( plaintext: string, key: Buffer )
| 9 | * @param key - 32-byte encryption key |
| 10 | */ |
| 11 | export async function encrypt( |
| 12 | plaintext: string, |
| 13 | key: Buffer |
| 14 | ): Promise<{ encrypted: string; iv: string }> { |
| 15 | assertKey(key) |
| 16 | |
| 17 | const iv = randomBytes(16) |
| 18 | const cipher = createCipheriv('aes-256-gcm', key, iv, { authTagLength: 16 }) |
| 19 | let encrypted = cipher.update(plaintext, 'utf8', 'hex') |
| 20 | encrypted += cipher.final('hex') |
| 21 | |
| 22 | const authTag = cipher.getAuthTag() |
| 23 | const ivHex = iv.toString('hex') |
| 24 | |
| 25 | return { |
| 26 | encrypted: `${ivHex}:${encrypted}:${authTag.toString('hex')}`, |
| 27 | iv: ivHex, |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | /** |
| 32 | * AES-256-GCM decryption primitive. Expects input produced by {@link encrypt} |
no test coverage detected