UNPKG

2.68 kBPlain TextView Raw
1import * as crypto from 'crypto'
2import { _stringMapEntries, StringMap } from '@naturalcycles/js-lib'
3import { md5 } from './hash.util'
4
5const algorithm = 'aes-256-cbc'
6
7/**
8 * Using aes-256-cbc
9 */
10export function encryptRandomIVBuffer(input: Buffer, secretKeyBase64: string): Buffer {
11 // md5 to match aes-256 key length of 32 bytes
12 const key = md5(Buffer.from(secretKeyBase64, 'base64'))
13
14 // Random iv to achieve non-deterministic encryption (but deterministic decryption)
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 * Using aes-256-cbc
23 */
24export function decryptRandomIVBuffer(input: Buffer, secretKeyBase64: string): Buffer {
25 // md5 to match aes-256 key length of 32 bytes
26 const key = md5(Buffer.from(secretKeyBase64, 'base64'))
27
28 // iv is first 16 bytes of encrypted buffer, the rest is payload
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 * Decrypts all object values.
39 * Returns object with decrypted values.
40 */
41export 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
52export 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 * Using aes-256-cbc
65 */
66export 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 * Using aes-256-cbc
74 */
75export 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
81function 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}