// @ts-check import { scryptSync, createCipheriv } from "crypto"; import { Buffer } from "buffer"; import grabKeys from "../../utils/grab-keys"; type Param = { data: string; encryptionKey?: string; encryptionSalt?: string; }; /** * # Encrypt String */ export default function encrypt({ data, encryptionKey, encryptionSalt, }: Param): string | null { if (!data?.match(/./)) { console.log("Encryption string is invalid"); return data; } const { key: encrptKey, salt, keyLen, algorithm, bufferAllocSize, } = grabKeys({ encryptionKey }); if (!encrptKey?.match(/.{8,}/)) { console.log("Encryption key is invalid"); return data; } if (!salt?.match(/.{8,}/)) { console.log("Encryption salt is invalid"); return data; } const password = encrptKey; let key = scryptSync(password, salt, keyLen); let iv = Buffer.alloc(bufferAllocSize, 0); const cipher = createCipheriv(algorithm, key, iv); try { let encrypted = cipher.update(data, "utf8", "hex"); encrypted += cipher.final("hex"); return encrypted; } catch (error: any) { console.log("Error in encrypting =>", error.message); return data; } }