-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
74 lines (64 loc) · 2.17 KB
/
index.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const {
randomBytes,
createCipheriv,
createDecipheriv,
createHash
} = require('crypto');
module.exports = class Instance {
constructor(key) {
if (typeof key !== 'string' || !key) throw new TypeError('Invalid key provided, must a non-empty string!');
this.cipher = 'aes-256-ctr';
this.encoding = 'base64';
this.hash = 'sha512';
this.key = key;
};
encrypt(content) {
if (!content) throw new TypeError('Invalid content provided, must be non-empty string or buffer!');
const iv = randomBytes(16);
const cipher = createCipheriv(
this.cipher,
createHash(this.hash)
.update(this.key)
.digest(this.encoding)
.slice(0, 32), iv
);
if (typeof content === 'string') {
return Buffer.concat([
iv,
cipher.update(Buffer.from(content)),
cipher.final()
]).toString(this.encoding);
} else if (Buffer.isBuffer(content)) {
return Buffer.concat([
iv,
cipher.update(content),
cipher.final()
]);
} else throw new TypeError('Invalid content provided, must be non-empty string or buffer!');
};
decrypt(content) {
if (!content) throw new TypeError('Invalid content provided, must be non-empty string or buffer!');
const input = Buffer.from(
content,
this.encoding
);
const decipher = createDecipheriv(
this.cipher,
createHash(this.hash)
.update(this.key)
.digest(this.encoding)
.slice(0, 32),
input.subarray(0, 16)
);
if (typeof content === 'string') {
return decipher.update(
input.subarray(16)
) + decipher.final();
} else if (Buffer.isBuffer(content)) {
return Buffer.concat([
decipher.update(content),
decipher.final()
]);
} else throw new TypeError('Invalid content provided, must be non-empty string or buffer!');
};
};