dsql-admin/dsql-app/package-shared/functions/dsql/encrypt.ts

59 lines
1.6 KiB
TypeScript
Raw Normal View History

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