datasquirel/package-shared/functions/dsql/encrypt.js

56 lines
1.6 KiB
JavaScript
Raw Normal View History

2023-09-21 14:00:04 +00:00
// @ts-check
const { scryptSync, createCipheriv } = require("crypto");
const { Buffer } = require("buffer");
/**
*
* @param {object} param0
* @param {string} param0.data
2024-12-06 10:31:24 +00:00
* @param {string} [param0.encryptionKey]
* @param {string} [param0.encryptionSalt]
2023-09-21 14:00:04 +00:00
* @returns {string | null}
*/
const encrypt = ({ data, encryptionKey, encryptionSalt }) => {
if (!data?.match(/./)) {
console.log("Encryption string is invalid");
return data;
}
2024-12-06 10:31:24 +00:00
const finalEncryptionKey =
encryptionKey || process.env.DSQL_ENCRYPTION_PASSWORD;
const finalEncryptionSalt =
encryptionSalt || process.env.DSQL_ENCRYPTION_SALT;
const finalKeyLen = process.env.DSQL_ENCRYPTION_KEY_LENGTH
? Number(process.env.DSQL_ENCRYPTION_KEY_LENGTH)
: 24;
if (!finalEncryptionKey?.match(/.{8,}/)) {
2023-09-21 14:00:04 +00:00
console.log("Encryption key is invalid");
return data;
}
2024-12-06 10:31:24 +00:00
if (!finalEncryptionSalt?.match(/.{8,}/)) {
2023-09-21 14:00:04 +00:00
console.log("Encryption salt is invalid");
return data;
}
const algorithm = "aes-192-cbc";
2024-12-06 10:31:24 +00:00
const password = finalEncryptionKey;
2023-09-21 14:00:04 +00:00
2024-12-06 10:31:24 +00:00
let key = scryptSync(password, finalEncryptionSalt, finalKeyLen);
2023-09-21 14:00:04 +00:00
let iv = Buffer.alloc(16, 0);
2024-10-18 04:15:04 +00:00
// @ts-ignore
2023-09-21 14:00:04 +00:00
const cipher = createCipheriv(algorithm, key, iv);
try {
let encrypted = cipher.update(data, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
} catch (/** @type {*} */ error) {
console.log("Error in encrypting =>", error.message);
return data;
}
};
module.exports = encrypt;