dsql-admin/dsql-app/package-shared/functions/dsql/encrypt.js

56 lines
1.6 KiB
JavaScript
Raw Normal View History

2024-12-06 13:24:26 +00:00
// @ts-check
const { scryptSync, createCipheriv } = require("crypto");
const { Buffer } = require("buffer");
/**
*
* @param {object} param0
* @param {string} param0.data
* @param {string} [param0.encryptionKey]
* @param {string} [param0.encryptionSalt]
* @returns {string | null}
*/
const encrypt = ({ data, encryptionKey, encryptionSalt }) => {
if (!data?.match(/./)) {
console.log("Encryption string is invalid");
return data;
}
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,}/)) {
console.log("Encryption key is invalid");
return data;
}
if (!finalEncryptionSalt?.match(/.{8,}/)) {
console.log("Encryption salt is invalid");
return data;
}
const algorithm = "aes-192-cbc";
const password = finalEncryptionKey;
let key = scryptSync(password, finalEncryptionSalt, finalKeyLen);
let iv = Buffer.alloc(16, 0);
// @ts-ignore
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;