1 | 'use strict';
|
2 |
|
3 | const crypto = require('crypto');
|
4 |
|
5 | function decrypt (text, secret, algorithm = 'aes-256-cbc') {
|
6 | let decrypted = null;
|
7 | secret = secret.replace(/-/g, '').substring(0, 32);
|
8 | const textParts = text.split(':');
|
9 | const iv = Buffer.from(textParts.shift(), 'hex');
|
10 | const encryptedText = Buffer.from(textParts.join(':'), 'hex');
|
11 | const decipher = crypto.createDecipheriv(algorithm, secret, iv);
|
12 | decrypted = decipher.update(encryptedText);
|
13 |
|
14 | decrypted = Buffer.concat([ decrypted, decipher.final() ]).toString();
|
15 |
|
16 | return decrypted;
|
17 | }
|
18 |
|
19 | function encrypt (text, secret, algorithm = 'aes-256-cbc', ivLength = 16) {
|
20 | let encrypted = null;
|
21 | secret = secret.replace(/-/g, '').substring(0, 32);
|
22 | const iv = crypto.randomBytes(ivLength);
|
23 | const cipher = crypto.createCipheriv(algorithm, secret, iv);
|
24 | encrypted = cipher.update(text);
|
25 | encrypted = Buffer.concat([ encrypted, cipher.final() ]);
|
26 | encrypted = `${ iv.toString('hex') }:${ encrypted.toString('hex') }`;
|
27 |
|
28 | return encrypted;
|
29 | }
|
30 |
|
31 | function sha1 (input) {
|
32 | if (typeof input !== 'string') {
|
33 | input = JSON.stringify(input);
|
34 | }
|
35 | return crypto.createHash('sha1').update(input).
|
36 | digest('hex');
|
37 | }
|
38 |
|
39 | function sha256 (input) {
|
40 | if (typeof input !== 'string') {
|
41 | input = JSON.stringify(input);
|
42 | }
|
43 | return crypto.createHash('sha256').update(input).
|
44 | digest('hex');
|
45 | }
|
46 |
|
47 | module.exports = {
|
48 | decrypt,
|
49 | encrypt,
|
50 | sha1,
|
51 | sha256,
|
52 | };
|