// @ts-check import { scryptSync, createDecipheriv } from "crypto"; import { Buffer } from "buffer"; import grabKeys from "../../utils/grab-keys"; type Param = { encryptedString: string; encryptionKey?: string; encryptionSalt?: string; debug?: boolean; }; /** * # Decrypt Function */ export default function decrypt({ encryptedString, encryptionKey, encryptionSalt, debug, }: Param) { if (!encryptedString?.match(/./)) { if (debug) console.log("Encrypted string is invalid"); return encryptedString; } const { key: encrptKey, salt, keyLen, algorithm, bufferAllocSize, } = grabKeys({ encryptionKey, encryptionSalt }); if (!encrptKey?.match(/.{8,}/)) { if (debug) console.log("Decrption key is invalid"); return encryptedString; } if (!salt?.match(/.{8,}/)) { if (debug) console.log("Decrption salt is invalid"); return encryptedString; } let key = scryptSync(encrptKey, salt, keyLen); let iv = Buffer.alloc(bufferAllocSize, 0); const decipher = createDecipheriv(algorithm, key, iv); try { let decrypted = decipher.update(encryptedString, "hex", "utf8"); decrypted += decipher.final("utf8"); return decrypted; } catch (error: any) { if (debug) { console.log("Error Decrypting data", error as Error); } return encryptedString; } }