1 | import * as crypto from 'crypto'
|
2 | import { md5 } from './hash.util'
|
3 |
|
4 | const algorithm = 'aes-256-cbc'
|
5 |
|
6 |
|
7 |
|
8 |
|
9 | export function encryptRandomIVBuffer(input: Buffer, secretKeyBase64: string): Buffer {
|
10 | const key = aes256Key(secretKeyBase64)
|
11 |
|
12 |
|
13 |
|
14 | const iv = crypto.randomBytes(16)
|
15 |
|
16 | const cipher = crypto.createCipheriv(algorithm, key, iv)
|
17 |
|
18 | return Buffer.concat([iv, cipher.update(input), cipher.final()])
|
19 | }
|
20 |
|
21 |
|
22 |
|
23 |
|
24 | export function decryptRandomIVBuffer(input: Buffer, secretKeyBase64: string): Buffer {
|
25 | const key = aes256Key(secretKeyBase64)
|
26 |
|
27 |
|
28 | const iv = input.slice(0, 16)
|
29 | const payload = input.slice(16)
|
30 |
|
31 | const decipher = crypto.createDecipheriv(algorithm, key, iv)
|
32 |
|
33 | return Buffer.concat([decipher.update(payload), decipher.final()])
|
34 | }
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | export function decryptString(str: string, secretKey: string): string {
|
40 | const { algorithm, key, iv } = getCryptoParams(secretKey)
|
41 | const decipher = crypto.createDecipheriv(algorithm, key, iv)
|
42 | let decrypted = decipher.update(str, 'base64', 'utf8')
|
43 | return (decrypted += decipher.final('utf8'))
|
44 | }
|
45 |
|
46 |
|
47 |
|
48 |
|
49 | export function encryptString(str: string, secretKey: string): string {
|
50 | const { algorithm, key, iv } = getCryptoParams(secretKey)
|
51 | const cipher = crypto.createCipheriv(algorithm, key, iv)
|
52 | let encrypted = cipher.update(str, 'utf8', 'base64')
|
53 | return (encrypted += cipher.final('base64'))
|
54 | }
|
55 |
|
56 | function getCryptoParams(secretKey: string): { algorithm: string; key: string; iv: string } {
|
57 | const key = md5(secretKey)
|
58 | const iv = md5(secretKey + key).slice(0, 16)
|
59 | return { algorithm, key, iv }
|
60 | }
|
61 |
|
62 | function aes256Key(secretKeyBase64: string): string {
|
63 |
|
64 | return md5(Buffer.from(secretKeyBase64, 'base64'))
|
65 | }
|