1 | import * as crypto from 'crypto'
|
2 | import { _stringMapEntries, StringMap } from '@naturalcycles/js-lib'
|
3 | import { md5 } from './hash.util'
|
4 |
|
5 | const algorithm = 'aes-256-cbc'
|
6 |
|
7 |
|
8 |
|
9 |
|
10 | export function encryptRandomIVBuffer(input: Buffer, secretKeyBase64: string): Buffer {
|
11 |
|
12 | const key = md5(Buffer.from(secretKeyBase64, 'base64'))
|
13 |
|
14 |
|
15 | const iv = crypto.randomBytes(16)
|
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 |
|
26 | const key = md5(Buffer.from(secretKeyBase64, 'base64'))
|
27 |
|
28 |
|
29 | const iv = input.slice(0, 16)
|
30 | const payload = input.slice(16)
|
31 |
|
32 | const decipher = crypto.createDecipheriv(algorithm, key, iv)
|
33 |
|
34 | return Buffer.concat([decipher.update(payload), decipher.final()])
|
35 | }
|
36 |
|
37 |
|
38 |
|
39 |
|
40 |
|
41 | export function decryptObject(obj: StringMap, secretKey: string): StringMap {
|
42 | const { key, iv } = getCryptoParams(secretKey)
|
43 |
|
44 | const r: StringMap = {}
|
45 | _stringMapEntries(obj).forEach(([k, v]) => {
|
46 | const decipher = crypto.createDecipheriv(algorithm, key, iv)
|
47 | r[k] = decipher.update(v, 'base64', 'utf8') + decipher.final('utf8')
|
48 | })
|
49 | return r
|
50 | }
|
51 |
|
52 | export function encryptObject(obj: StringMap, secretKey: string): StringMap {
|
53 | const { key, iv } = getCryptoParams(secretKey)
|
54 |
|
55 | const r: StringMap = {}
|
56 | _stringMapEntries(obj).forEach(([k, v]) => {
|
57 | const cipher = crypto.createCipheriv(algorithm, key, iv)
|
58 | r[k] = cipher.update(v, 'utf8', 'base64') + cipher.final('base64')
|
59 | })
|
60 | return r
|
61 | }
|
62 |
|
63 |
|
64 |
|
65 |
|
66 | export function decryptString(str: string, secretKey: string): string {
|
67 | const { key, iv } = getCryptoParams(secretKey)
|
68 | const decipher = crypto.createDecipheriv(algorithm, key, iv)
|
69 | return decipher.update(str, 'base64', 'utf8') + decipher.final('utf8')
|
70 | }
|
71 |
|
72 |
|
73 |
|
74 |
|
75 | export function encryptString(str: string, secretKey: string): string {
|
76 | const { key, iv } = getCryptoParams(secretKey)
|
77 | const cipher = crypto.createCipheriv(algorithm, key, iv)
|
78 | return cipher.update(str, 'utf8', 'base64') + cipher.final('base64')
|
79 | }
|
80 |
|
81 | function getCryptoParams(secretKey: string): { key: string; iv: string } {
|
82 | const key = md5(secretKey)
|
83 | const iv = md5(secretKey + key).slice(0, 16)
|
84 | return { key, iv }
|
85 | }
|