UNPKG

1.21 kBPlain TextView Raw
1import * as crypto from 'crypto'
2import { md5 } from './hash.util'
3
4// const randomBytes = promisify(crypto.randomBytes)
5
6function aes256Key(secretKeyBase64: string): string {
7 // md5 to match aes-256 key length of 32 bytes
8 return md5(Buffer.from(secretKeyBase64, 'base64'))
9}
10
11export function encryptRandomIVBuffer(
12 input: Buffer,
13 secretKeyBase64: string,
14 algorithm = 'aes-256-cbc',
15): Buffer {
16 const key = aes256Key(secretKeyBase64)
17
18 // Random iv to achieve non-deterministic encryption (but deterministic decryption)
19 // const iv = await randomBytes(16)
20 const iv = crypto.randomBytes(16) // use sync method here for speed
21
22 const cipher = crypto.createCipheriv(algorithm, key, iv)
23
24 return Buffer.concat([iv, cipher.update(input), cipher.final()])
25}
26
27export function decryptRandomIVBuffer(
28 input: Buffer,
29 secretKeyBase64: string,
30 algorithm = 'aes-256-cbc',
31): Buffer {
32 const key = aes256Key(secretKeyBase64)
33
34 // iv is first 16 bytes of encrypted buffer, the rest is payload
35 const iv = input.slice(0, 16)
36 const payload = input.slice(16)
37
38 const decipher = crypto.createDecipheriv(algorithm, key, iv)
39
40 return Buffer.concat([decipher.update(payload), decipher.final()])
41}