2024-12-06 13:24:26 +00:00
|
|
|
// @ts-check
|
|
|
|
|
2025-01-13 08:00:21 +00:00
|
|
|
import { scryptSync, createDecipheriv } from "crypto";
|
|
|
|
import { Buffer } from "buffer";
|
2025-01-14 15:27:08 +00:00
|
|
|
import grabKeys from "../../utils/grab-keys";
|
2025-01-13 08:00:21 +00:00
|
|
|
|
|
|
|
type Param = {
|
|
|
|
encryptedString: string;
|
|
|
|
encryptionKey?: string;
|
|
|
|
encryptionSalt?: string;
|
|
|
|
};
|
2024-12-06 13:24:26 +00:00
|
|
|
|
|
|
|
/**
|
2025-01-13 08:00:21 +00:00
|
|
|
* # Decrypt Function
|
2024-12-06 13:24:26 +00:00
|
|
|
*/
|
2025-01-13 08:00:21 +00:00
|
|
|
export default function decrypt({
|
|
|
|
encryptedString,
|
|
|
|
encryptionKey,
|
|
|
|
encryptionSalt,
|
|
|
|
}: Param) {
|
2024-12-06 13:24:26 +00:00
|
|
|
if (!encryptedString?.match(/./)) {
|
|
|
|
console.log("Encrypted string is invalid");
|
|
|
|
return encryptedString;
|
|
|
|
}
|
|
|
|
|
2025-01-14 15:27:08 +00:00
|
|
|
const {
|
|
|
|
key: encrptKey,
|
|
|
|
salt,
|
|
|
|
keyLen,
|
|
|
|
algorithm,
|
|
|
|
bufferAllocSize,
|
|
|
|
} = grabKeys({ encryptionKey });
|
2024-12-06 13:24:26 +00:00
|
|
|
|
2025-01-14 15:27:08 +00:00
|
|
|
if (!encrptKey?.match(/.{8,}/)) {
|
2024-12-06 13:24:26 +00:00
|
|
|
console.log("Decrption key is invalid");
|
|
|
|
return encryptedString;
|
|
|
|
}
|
|
|
|
|
2025-01-14 15:27:08 +00:00
|
|
|
if (!salt?.match(/.{8,}/)) {
|
2024-12-06 13:24:26 +00:00
|
|
|
console.log("Decrption salt is invalid");
|
|
|
|
return encryptedString;
|
|
|
|
}
|
|
|
|
|
2025-01-14 15:27:08 +00:00
|
|
|
let key = scryptSync(encrptKey, salt, keyLen);
|
|
|
|
let iv = Buffer.alloc(bufferAllocSize, 0);
|
2025-01-13 08:00:21 +00:00
|
|
|
|
2024-12-06 13:24:26 +00:00
|
|
|
const decipher = createDecipheriv(algorithm, key, iv);
|
|
|
|
|
|
|
|
try {
|
|
|
|
let decrypted = decipher.update(encryptedString, "hex", "utf8");
|
|
|
|
decrypted += decipher.final("utf8");
|
|
|
|
return decrypted;
|
2025-01-13 08:00:21 +00:00
|
|
|
} catch (error: any) {
|
2024-12-06 13:24:26 +00:00
|
|
|
console.log("Error in decrypting =>", error.message);
|
|
|
|
return encryptedString;
|
|
|
|
}
|
2025-01-13 08:00:21 +00:00
|
|
|
}
|