1 | import * as crypto from 'crypto'
|
2 | import { md5 } from './hash.util'
|
3 |
|
4 |
|
5 |
|
6 | function aes256Key(secretKeyBase64: string): string {
|
7 |
|
8 | return md5(Buffer.from(secretKeyBase64, 'base64'))
|
9 | }
|
10 |
|
11 | export function encryptRandomIVBuffer(
|
12 | input: Buffer,
|
13 | secretKeyBase64: string,
|
14 | algorithm = 'aes-256-cbc',
|
15 | ): Buffer {
|
16 | const key = aes256Key(secretKeyBase64)
|
17 |
|
18 |
|
19 |
|
20 | const iv = crypto.randomBytes(16)
|
21 |
|
22 | const cipher = crypto.createCipheriv(algorithm, key, iv)
|
23 |
|
24 | return Buffer.concat([iv, cipher.update(input), cipher.final()])
|
25 | }
|
26 |
|
27 | export function decryptRandomIVBuffer(
|
28 | input: Buffer,
|
29 | secretKeyBase64: string,
|
30 | algorithm = 'aes-256-cbc',
|
31 | ): Buffer {
|
32 | const key = aes256Key(secretKeyBase64)
|
33 |
|
34 |
|
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 | }
|