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

61 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, createCipheriv } from "crypto";
import { Buffer } from "buffer";
type Param = {
data: string;
encryptionKey?: string;
encryptionSalt?: string;
};
2023-09-21 14:00:04 +00:00
/**
2025-01-10 19:10:28 +00:00
* # Encrypt String
2023-09-21 14:00:04 +00:00
*/
2025-01-10 19:10:28 +00:00
export default function encrypt({
data,
encryptionKey,
encryptionSalt,
}: Param): string | null {
2023-09-21 14:00:04 +00:00
if (!data?.match(/./)) {
console.log("Encryption string is invalid");
return data;
}
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("Encryption key is invalid");
return data;
}
2024-12-06 10:31:24 +00:00
if (!finalEncryptionSalt?.match(/.{8,}/)) {
2023-09-21 14:00:04 +00:00
console.log("Encryption salt is invalid");
return data;
}
const algorithm = "aes-192-cbc";
2024-12-06 10:31:24 +00:00
const password = finalEncryptionKey;
2023-09-21 14:00:04 +00:00
2024-12-06 10:31:24 +00:00
let key = scryptSync(password, finalEncryptionSalt, finalKeyLen);
2023-09-21 14:00:04 +00:00
let iv = Buffer.alloc(16, 0);
2024-10-18 04:15:04 +00:00
// @ts-ignore
2023-09-21 14:00:04 +00:00
const cipher = createCipheriv(algorithm, key, iv);
try {
let encrypted = cipher.update(data, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
2025-01-10 19:10:28 +00:00
} catch (/** @type {*} */ error: any) {
2023-09-21 14:00:04 +00:00
console.log("Error in encrypting =>", error.message);
return data;
}
2025-01-10 19:10:28 +00:00
}
2023-09-21 14:00:04 +00:00
module.exports = encrypt;