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

59 lines
1.3 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";
2025-01-14 15:27:08 +00:00
import grabKeys from "../../utils/grab-keys";
2025-01-13 08:00:21 +00:00
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;
}
2025-01-14 15:27:08 +00:00
const {
key: encrptKey,
salt,
keyLen,
algorithm,
bufferAllocSize,
} = grabKeys({ encryptionKey });
2024-12-06 13:24:26 +00:00
2025-01-14 15:27:08 +00:00
if (!encrptKey?.match(/.{8,}/)) {
2024-12-06 13:24:26 +00:00
console.log("Encryption key is invalid");
return data;
}
2025-01-14 15:27:08 +00:00
if (!salt?.match(/.{8,}/)) {
2024-12-06 13:24:26 +00:00
console.log("Encryption salt is invalid");
return data;
}
2025-01-14 15:27:08 +00:00
const password = encrptKey;
let key = scryptSync(password, salt, keyLen);
let iv = Buffer.alloc(bufferAllocSize, 0);
2024-12-06 13:24:26 +00:00
const cipher = createCipheriv(algorithm, key, iv);
try {
let encrypted = cipher.update(data, "utf8", "hex");
encrypted += cipher.final("hex");
return encrypted;
2025-01-14 15:27:08 +00:00
} catch (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
}