datasquirel/functions/encrypt.js

46 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-08-12 13:36:18 +00:00
// @ts-check
2023-05-06 11:14:09 +00:00
const { scryptSync, createCipheriv } = require("crypto");
const { Buffer } = require("buffer");
2023-08-13 13:00:04 +00:00
/**
*
* @param {object} param0
* @param {string} param0.data
* @param {string} param0.encryptionKey
* @param {string} param0.encryptionSalt
* @returns {string | null}
*/
2023-05-06 11:14:09 +00:00
const encrypt = ({ data, encryptionKey, encryptionSalt }) => {
2023-08-13 13:00:04 +00:00
if (!data?.match(/./)) {
console.log("Encryption string is invalid");
return data;
}
2023-08-12 13:36:18 +00:00
if (!encryptionKey?.match(/.{8,}/)) {
console.log("Encryption key is invalid");
return data;
}
if (!encryptionSalt?.match(/.{8,}/)) {
console.log("Encryption salt is invalid");
return data;
}
2023-05-06 11:14:09 +00:00
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;
2023-08-13 13:56:56 +00:00
} catch (/** @type {*} */ error) {
2023-08-13 13:00:04 +00:00
console.log("Error in encrypting =>", error.message);
return data;
2023-05-06 11:14:09 +00:00
}
};
module.exports = encrypt;