datasquirel/functions/decrypt.js

47 lines
1.2 KiB
JavaScript
Raw Normal View History

2023-08-13 11:06:14 +00:00
// @ts-check
2023-05-06 11:14:09 +00:00
const { scryptSync, createDecipheriv } = require("crypto");
const { Buffer } = require("buffer");
2023-08-13 11:06:14 +00:00
/**
*
* @param {object} param0
* @param {string} param0.encryptedString
* @param {string} param0.encryptionKey
* @param {string} param0.encryptionSalt
* @returns
*/
2023-05-06 11:14:09 +00:00
const decrypt = ({ encryptedString, encryptionKey, encryptionSalt }) => {
2023-08-13 11:11:17 +00:00
if (!encryptedString?.match(/./)) {
2023-08-13 10:58:33 +00:00
console.log("Encrypted string is invalid");
2023-08-13 11:06:14 +00:00
return encryptedString;
2023-08-13 10:58:33 +00:00
}
2023-05-06 11:14:09 +00:00
2023-08-12 16:35:59 +00:00
if (!encryptionKey?.match(/.{8,}/)) {
console.log("Decrption key is invalid");
2023-08-13 11:06:14 +00:00
return encryptedString;
2023-08-12 16:35:59 +00:00
}
2023-08-13 10:58:33 +00:00
2023-08-12 16:35:59 +00:00
if (!encryptionSalt?.match(/.{8,}/)) {
console.log("Decrption salt is invalid");
2023-08-13 11:06:14 +00:00
return encryptedString;
2023-08-12 16:35:59 +00:00
}
2023-08-13 10:58:33 +00:00
const algorithm = "aes-192-cbc";
let key = scryptSync(encryptionKey, encryptionSalt, 24);
2023-05-06 11:14:09 +00:00
let iv = Buffer.alloc(16, 0);
const decipher = createDecipheriv(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
} catch (error) {
2023-08-13 10:47:53 +00:00
console.log("Error in decrypting =>", error.message);
2023-08-13 11:06:14 +00:00
return encryptedString;
2023-05-06 11:14:09 +00:00
}
};
module.exports = decrypt;