"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const CIPHER_TYPE = 'aes-256-cbc';
class NodeAes {
    encrypt(message, key) {
        const salt = crypto_1.randomBytes(8);
        const pbe = this.generateKey(Buffer.from(key), salt);
        const saltBlock = Buffer.concat([Buffer.from('Salted__'), salt]);
        const cipher = crypto_1.createCipheriv(CIPHER_TYPE, pbe.key, pbe.iv);
        const enc = cipher.update(message, 'utf8');
        return Buffer.concat([saltBlock, enc, cipher.final()])
            .toString('base64')
            .match(/.{1,60}/g).join("\n");
    }
    decrypt(message, key) {
        const buffer = Buffer.from(message, 'base64');
        const salt = buffer.slice(8, 16);
        const data = buffer.slice(16, buffer.length);
        const pbe = this.generateKey(Buffer.from(key), salt);
        const cipher = crypto_1.createDecipheriv(CIPHER_TYPE, pbe.key, pbe.iv);
        let dec = cipher.update(data);
        return Buffer.concat([dec, cipher.final()]).toString('utf8');
    }
    md5(buffer) {
        return crypto_1.createHash('md5').update(buffer).digest();
    }
    generateKey(password, salt) {
        const md5Hash = [];
        const data00 = Buffer.concat([password, salt]);
        md5Hash[0] = this.md5(data00);
        let result = md5Hash[0];
        for (let i = 1; i < 3; i++) {
            md5Hash[i] = this.md5(Buffer.concat([md5Hash[i - 1], data00]));
            result = Buffer.concat([result, md5Hash[i]]);
        }
        return {
            key: result.slice(0, 32),
            iv: result.slice(32, 48)
        };
    }
}
exports.NodeAes = NodeAes;
