aes-encryption-128
Version:
Simple aes encryption algorithm
34 lines (29 loc) • 924 B
JavaScript
const crypto = require("crypto");
// Encryption function
exports.encrypt = function (text, key) {
const keyBuffer = Buffer.alloc(16); // 16 bytes for AES-128
const keyBytes = Buffer.from(key, "utf8");
keyBytes.copy(keyBuffer);
const cipher = crypto.createCipheriv(
"aes-128-cbc",
keyBuffer,
Buffer.alloc(16),
);
let encrypted = cipher.update(text, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
};
// Decryption function
exports.decrypt = function (encryptedText, key) {
const keyBuffer = Buffer.alloc(16); // 16 bytes for AES-128
const keyBytes = Buffer.from(key, "utf8");
keyBytes.copy(keyBuffer);
const decipher = crypto.createDecipheriv(
"aes-128-cbc",
keyBuffer,
Buffer.alloc(16),
);
let decrypted = decipher.update(encryptedText, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
};