1 | "use strict";
|
2 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
3 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
4 | };
|
5 | Object.defineProperty(exports, "__esModule", { value: true });
|
6 | const crypto_1 = __importDefault(require("crypto"));
|
7 | const IV_LENGTH = 16;
|
8 | class Cipher {
|
9 | constructor(key, config = { cipherAlgo: 'aes-256-cbc', digestAlgo: 'sha256', encoding: 'utf8' }) {
|
10 | this.key = key;
|
11 | this.config = config;
|
12 | this.encrypt = (message) => {
|
13 | const iv = crypto_1.default.randomBytes(IV_LENGTH);
|
14 | const cipher = crypto_1.default.createCipheriv(this.config.cipherAlgo, this.key, iv);
|
15 | const encrypted = Buffer.concat([cipher.update(message), cipher.final()]);
|
16 | return [iv.toString('hex'), encrypted.toString('hex')].join(':');
|
17 | };
|
18 | this.decrypt = (encryptedMessage) => {
|
19 | const textParts = encryptedMessage.split(':');
|
20 | const iv = new Buffer(textParts.shift(), 'hex');
|
21 | const encryptedText = new Buffer(textParts.join(':'), 'hex');
|
22 | const decipher = crypto_1.default.createDecipheriv('aes-256-cbc', new Buffer(this.key), iv);
|
23 | const decrypted = decipher.update(encryptedText);
|
24 | return Buffer.concat([decrypted, decipher.final()]).toString();
|
25 | };
|
26 | this.digest = (message) => {
|
27 | return crypto_1.default
|
28 | .createHmac(this.config.digestAlgo, this.key)
|
29 | .update(new Buffer(message, this.config.encoding))
|
30 | .digest('hex');
|
31 | };
|
32 | if (!key || !key.length) {
|
33 | throw new Error('Invalid key length');
|
34 | }
|
35 | }
|
36 | }
|
37 | exports.default = Cipher;
|