-
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcipher.js
More file actions
74 lines (62 loc) · 1.89 KB
/
cipher.js
File metadata and controls
74 lines (62 loc) · 1.89 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
const crypto = require('crypto');
const hD = {};
const hE = {};
module.exports = function getCipher(key, salt, algorithm = 'aes-192-cbc') {
if (!key || !algorithm || !salt) return {};
return {
decrypt(encrypted) {
if (hD[encrypted]) return hD[encrypted];
return new Promise((res) => {
try {
const decipher = crypto.createDecipheriv(
algorithm,
crypto.scryptSync(key, salt, 24),
Buffer.alloc(16, 0),
);
let decrypted = '';
decipher.on('readable', () => {
let chunk;
// eslint-disable-next-line no-cond-assign
while ((chunk = decipher.read()) !== null) decrypted += chunk.toString('utf8');
});
decipher.on('end', () => {
hD[encrypted] = decrypted;
res(decrypted);
});
decipher.write(encrypted, 'hex');
decipher.end();
} catch (err) {
console.log(`Can't decrypt "${encrypted}"`, err.message);
res(encrypted);
}
});
},
encrypt(message) {
if (hE[message]) return hE[message];
return new Promise((res) => {
try {
const cipher = crypto.createCipheriv(
algorithm,
crypto.scryptSync(key, salt, 24),
Buffer.alloc(16, 0),
);
let encrypted = '';
cipher.on('readable', () => {
let chunk;
// eslint-disable-next-line no-cond-assign
while ((chunk = cipher.read()) !== null) encrypted += chunk.toString('hex');
});
cipher.on('end', () => {
hE[message] = encrypted;
res(encrypted);
});
cipher.write(message);
cipher.end();
} catch (err) {
console.log(`Can't encrypt "${message}"`, err.message);
res(message);
}
});
},
};
};