UNPKG

2.03 kBPlain TextView Raw
1import * as crypto from 'crypto'
2import { md5 } from './hash.util'
3
4const algorithm = 'aes-256-cbc'
5
6/**
7 * Using aes-256-cbc
8 */
9export function encryptRandomIVBuffer(input: Buffer, secretKeyBase64: string): Buffer {
10 const key = aes256Key(secretKeyBase64)
11
12 // Random iv to achieve non-deterministic encryption (but deterministic decryption)
13 // const iv = await randomBytes(16)
14 const iv = crypto.randomBytes(16) // use sync method here for speed
15
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 const key = aes256Key(secretKeyBase64)
26
27 // iv is first 16 bytes of encrypted buffer, the rest is payload
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 * Using aes-256-cbc
38 */
39export 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 * Using aes-256-cbc
48 */
49export 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
56function 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
62function aes256Key(secretKeyBase64: string): string {
63 // md5 to match aes-256 key length of 32 bytes
64 return md5(Buffer.from(secretKeyBase64, 'base64'))
65}