1 | const internal = require('./internal/encryption');
|
2 |
|
3 | module.exports = (options) => {
|
4 |
|
5 | const opt = options;
|
6 | if (!opt) throw Error('You have to specify options for encryption module');
|
7 |
|
8 | if (!opt.iterationCount) opt.iterationCount = 100000;
|
9 | else if (opt.iterationCount && typeof opt.iterationCount === 'string') opt.iterationCount = parseInt(opt.iterationCount, 10);
|
10 |
|
11 | if (!opt.password && !opt.encryptionKey) throw Error('You have to specify password or encryption key');
|
12 |
|
13 | if (opt.password && !opt.encryptionKey) {
|
14 | if (!opt.passwordSalt) {
|
15 | console.log('Warning: Default salt string used, you should specify passwordSalt option');
|
16 | opt.passwordSalt = 'PeterPan123';
|
17 | }
|
18 | opt.encryptionKey = internal.getKeyFromPassword(opt.password, opt.passwordSalt, 32, opt.iterationCount);
|
19 | }
|
20 |
|
21 | if (!opt.encryptionAlgorithm) opt.encryptionAlgorithm = 'aes-256-cbc';
|
22 |
|
23 | return {
|
24 | options,
|
25 | encrypt: (text) => new Promise((resolve) => {
|
26 | internal.encrypt(text, options.encryptionKey, options.encryptionAlgorithm, (err, result) => {
|
27 | if (err) throw err;
|
28 | resolve(result.toString('base64'));
|
29 | });
|
30 | }),
|
31 | decrypt: (encText) => new Promise((resolve) => {
|
32 | internal.decrypt(encText,
|
33 | options.encryptionKey,
|
34 | options.encryptionAlgorithm, (err, result) => {
|
35 | if (err) throw err;
|
36 | resolve(result);
|
37 | });
|
38 | }),
|
39 | };
|
40 | };
|