forked from ToolJet/ToolJet
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathservice.ts
More file actions
57 lines (45 loc) · 2.21 KB
/
service.ts
File metadata and controls
57 lines (45 loc) · 2.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import { Injectable } from '@nestjs/common';
import * as hkdf from 'futoin-hkdf';
import { IEncryptionService } from './interfaces/IService';
const crypto = require('crypto');
@Injectable()
export class EncryptionService implements IEncryptionService {
async encryptColumnValue(table: string, column: string, text: string): Promise<string> {
const derivedKey = this.#computeAttributeKey(table, column);
return this.#encrypt(text, derivedKey);
}
async decryptColumnValue(table: string, column: string, cipherText: string): Promise<string> {
const derivedKey = this.#computeAttributeKey(table, column);
return this.#decrypt(cipherText, derivedKey);
}
#encrypt(text: string, derivedKey: string): string {
const nonce = crypto.randomBytes(12);
const key = Buffer.from(derivedKey, 'hex');
const cipher = crypto.createCipheriv('aes-256-gcm', key, nonce);
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
const tag = cipher.getAuthTag();
const encryptedString = Buffer.concat([nonce, encrypted, tag]).toString('base64');
return encryptedString;
}
#decrypt(cipherText: string, derivedKey: string): string {
const key = Buffer.from(derivedKey, 'hex');
let ciphertext = Buffer.from(cipherText, 'base64');
const nonce = ciphertext.subarray(0, 12);
const auth_tag = ciphertext.subarray(-16);
ciphertext = ciphertext.subarray(12, -16);
const aesgcm = crypto.createDecipheriv('aes-256-gcm', key, nonce);
aesgcm.setAuthTag(auth_tag);
const plainText = aesgcm.update(ciphertext) + aesgcm.final();
return plainText;
}
// Generating separated keys for every column using the method used by Lockbox gem - https://github.com/ankane/lockbox
// This was needed when we migrated from Ruby on Rails to NestJS
#computeAttributeKey(table: string, column: string): string {
const key = Buffer.from(process.env.LOCKBOX_MASTER_KEY, 'hex');
const salt = Buffer.alloc(32, '´', 'ascii');
const info = Buffer.concat([salt, Buffer.from(`${column}_ciphertext`)]);
const derivedKey = hkdf(key, 32, { salt: table, info, hash: 'sha384' });
const finalDerivedKey = Buffer.from(derivedKey).toString('hex');
return finalDerivedKey;
}
}