datasquirel/functions/encrypt.js
2023-08-12 14:36:18 +01:00

33 lines
852 B
JavaScript

// @ts-check
const { scryptSync, createCipheriv } = require("crypto");
const { Buffer } = require("buffer");
const encrypt = ({ data, encryptionKey, encryptionSalt }) => {
if (!encryptionKey?.match(/.{8,}/)) {
console.log("Encryption key is invalid");
return data;
}
if (!encryptionSalt?.match(/.{8,}/)) {
console.log("Encryption salt is invalid");
return data;
}
const algorithm = "aes-192-cbc";
const password = encryptionKey;
let key = scryptSync(password, encryptionSalt, 24);
let iv = Buffer.alloc(16, 0);
const cipher = createCipheriv(algorithm, key, iv);
try {
let encrypted = cipher.update(data, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
} catch (error) {
return null;
}
};
module.exports = encrypt;