-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcrypto.js
53 lines (44 loc) · 1.36 KB
/
crypto.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
46
47
48
49
50
51
52
53
const crypto = require("crypto");
const _ = require("lodash");
class customCrypto {
#encryptionKey = undefined;
#encryptionIV = undefined;
constructor({ algorithm, customKey, customIV }) {
this.#encryptionKey = customKey
? Buffer.from(customKey, "hex")
: crypto.randomBytes(32);
this.#encryptionIV = customIV
? Buffer.from(customIV, "hex")
: crypto.randomBytes(16);
if (_.isString(customIV) === false || _.isString(customKey) === false) {
console.log(`Encryption Key: ${this.#encryptionKey.toString("hex")}`);
console.log(`Encryption IV: ${this.#encryptionIV.toString("hex")}`);
}
this.algorithm = algorithm || "aes-256-gcm";
}
encrypt(text) {
const cipher = crypto.createCipheriv(
this.algorithm,
this.#encryptionKey,
this.#encryptionIV
);
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
return {
iv: this.#encryptionIV.toString("hex"),
content: encrypted,
};
}
decrypt(hash) {
const decipher = crypto.createDecipheriv(
this.algorithm,
this.#encryptionKey,
Buffer.from(hash.iv || this.#encryptionIV, "hex")
);
const decrypted = Buffer.concat([
decipher.update(Buffer.from(hash.iv ? hash.content : hash, "hex")),
decipher.final(),
]);
return decrypted;
}
}
module.exports = customCrypto;