multi-layers-encryption
Version:
Encryption and decryption with multiple configurable layers
82 lines (64 loc) • 2.05 kB
text/typescript
import crypto from "crypto";
export type LayerConfig = {
algorithm: string; // เช่น 'aes-256-cbc', 'aes-192-cbc', 'des-ede3-cbc'
key: string;
salt?: string;
};
export class MultiLayerEncryption {
private layers: LayerConfig[];
constructor(layers: LayerConfig[]) {
this.layers = layers;
}
encrypt(content: string): string {
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: string): string {
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;
}
private getKeyLength(algorithm: string): number {
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;