UNPKG

multi-layers-encryption

Version:

Encryption and decryption with multiple configurable layers

59 lines (58 loc) 2.07 kB
import crypto from "crypto"; export class MultiLayerEncryption { constructor(layers) { this.layers = layers; } encrypt(content) { let result = content; for (const layer of this.layers) { const iv = layer.salt ? Buffer.from(layer.salt.padEnd(16, "0").slice(0, 16)) : crypto.randomBytes(16); const key = crypto .createHash("sha256") .update(layer.key) .digest() .subarray(0, this.getKeyLength(layer.algorithm)); const cipher = crypto.createCipheriv(layer.algorithm, key, iv); let encrypted = cipher.update(result, "utf8", "base64"); encrypted += cipher.final("base64"); result = JSON.stringify({ algorithm: layer.algorithm, iv: iv.toString("base64"), data: encrypted, }); } return result; } decrypt(content) { let result = content; for (let i = this.layers.length - 1; i >= 0; i--) { const layer = this.layers[i]; const parsed = JSON.parse(result); const iv = Buffer.from(parsed.iv, "base64"); const key = crypto .createHash("sha256") .update(layer.key) .digest() .subarray(0, this.getKeyLength(layer.algorithm)); const decipher = crypto.createDecipheriv(layer.algorithm, key, iv); let decrypted = decipher.update(parsed.data, "base64", "utf8"); decrypted += decipher.final("utf8"); result = decrypted; } return result; } getKeyLength(algorithm) { if (algorithm.includes("256")) return 32; if (algorithm.includes("192")) return 24; if (algorithm.includes("128")) return 16; if (algorithm.includes("des-ede3")) return 24; // 3DES return 16; // default } } export default MultiLayerEncryption;