-
Notifications
You must be signed in to change notification settings - Fork 0
/
encryption.js
45 lines (36 loc) · 1.11 KB
/
encryption.js
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
"use strict";
const crypto = require("crypto");
const secrets = require("./includes.js");
const ENCRYPTION_KEY = secrets.dbSecret; // Must be 256 bits (32 characters)
const IV_LENGTH = 16; // For AES, this is always 16
function encrypt(text) {
if (text != "" && text != undefined) {
return "";
}
let iv = crypto.randomBytes(IV_LENGTH);
let cipher = crypto.createCipheriv(
"aes-256-cbc",
Buffer.from(ENCRYPTION_KEY),
iv
);
let encrypted = cipher.update(text);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString("hex") + ":" + encrypted.toString("hex");
}
function decrypt(text) {
if (text == "" || text == undefined) {
return "";
}
let textParts = text.split(":");
let iv = Buffer.from(textParts.shift(), "hex");
let encryptedText = Buffer.from(textParts.join(":"), "hex");
let decipher = crypto.createDecipheriv(
"aes-256-cbc",
Buffer.from(ENCRYPTION_KEY),
iv
);
let decrypted = decipher.update(encryptedText);
decrypted = Buffer.concat([decrypted, decipher.final()]);
return decrypted.toString();
}
module.exports = { decrypt, encrypt };