const crypto = require("crypto");
const charset = "utf-8";
const format = "base64";
const iv = Buffer.alloc(8);
const transformation = "des-ede3-cbc";
function Encryption(secretKey) {
this.secretKey = secretKey;
}
Encryption.prototype.md5 = function (data) {
return crypto.createHash("md5").update(data, charset).digest();
};
Encryption.prototype.getCipherInstance = function () {
const digestPassword = this.md5(this.secretKey);
const keyBytes = Buffer.alloc(24);
keyBytes.fill(digestPassword);
let j = 0,
k = 16;
while (j < 8) {
keyBytes[k++] = keyBytes[j++];
}
return keyBytes;
};
Encryption.prototype.encrypt = function (data) {
const keyBytes = this.getCipherInstance();
const cipher = crypto.createCipheriv(transformation, keyBytes, iv);
const encrypted = cipher.update(data, charset, format);
return encrypted + cipher.final(format);
};
Encryption.prototype.decrypt = function (hashedData) {
const keyBytes = this.getCipherInstance();
const decipher = crypto.createDecipheriv(transformation, keyBytes, iv);
const decrypted = decipher.update(hashedData, format);
return decrypted + decipher.final();
};
// usage
const instance = new Encryption("test");
console.log(instance.encrypt("test-key"));
console.log(instance.decrypt("OykLQx3mPoQhTAjaoayFfg=="));