datasquirel/package-shared/functions/dsql/decrypt.ts

59 lines
1.6 KiB
TypeScript
Raw Normal View History

2023-09-21 14:00:04 +00:00
// @ts-check
2025-01-10 19:10:28 +00:00
import { scryptSync, createDecipheriv } from "crypto";
import { Buffer } from "buffer";
type Param = {
encryptedString: string;
encryptionKey?: string;
encryptionSalt?: string;
};
2023-09-21 14:00:04 +00:00
/**
2025-01-10 19:10:28 +00:00
* # Decrypt Function
2023-09-21 14:00:04 +00:00
*/
2025-01-10 19:10:28 +00:00
export default function decrypt({
encryptedString,
encryptionKey,
encryptionSalt,
}: Param) {
2023-09-21 14:00:04 +00:00
if (!encryptedString?.match(/./)) {
console.log("Encrypted string is invalid");
return encryptedString;
}
2024-12-06 10:31:24 +00:00
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,}/)) {
2023-09-21 14:00:04 +00:00
console.log("Decrption key is invalid");
return encryptedString;
}
2024-12-06 10:31:24 +00:00
if (!finalEncryptionSalt?.match(/.{8,}/)) {
2023-09-21 14:00:04 +00:00
console.log("Decrption salt is invalid");
return encryptedString;
}
const algorithm = "aes-192-cbc";
2024-12-06 10:31:24 +00:00
let key = scryptSync(finalEncryptionKey, finalEncryptionSalt, finalKeyLen);
2023-09-21 14:00:04 +00:00
let iv = Buffer.alloc(16, 0);
2025-01-10 19:10:28 +00:00
2023-09-21 14:00:04 +00:00
const decipher = createDecipheriv(algorithm, key, iv);
try {
let decrypted = decipher.update(encryptedString, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
2025-01-10 19:10:28 +00:00
} catch (error: any) {
2023-09-21 14:00:04 +00:00
console.log("Error in decrypting =>", error.message);
return encryptedString;
}
2025-01-10 19:10:28 +00:00
}