Start migration, and re-organizing files.

This commit is contained in:
mbaharip
2023-05-20 21:31:24 +07:00
parent c823f7f730
commit a234559321
59 changed files with 3263 additions and 939 deletions
+35 -11
View File
@@ -11,7 +11,9 @@ export function generateRandomEncryptionKey(): Promise<string> {
});
}
export function createEncryptionKey(passphrase: string): Promise<string> {
export function createEncryptionKey(
passphrase: string,
): Promise<string> {
return new Promise((resolve, reject) => {
const salt = crypto.randomBytes(16); // generate a random salt
const iterations = 100000; // number of PBKDF2 iterations
@@ -34,7 +36,8 @@ export function createEncryptionKey(passphrase: string): Promise<string> {
export function encrypt(
data: string,
encryptionKey: string = process.env.NEXT_PUBLIC_ENCRYPTION_KEY as string,
encryptionKey: string = process.env
.NEXT_PUBLIC_ENCRYPTION_KEY as string,
) {
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(
@@ -44,14 +47,19 @@ export function encrypt(
);
let encrypted = cipher.update(data);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return iv.toString("hex") + ":" + encrypted.toString("hex");
return (
iv.toString("hex") + ":" + encrypted.toString("hex")
);
}
export function decrypt(
encryptedData: string,
encryptionKey: string = process.env.NEXT_PUBLIC_ENCRYPTION_KEY as string,
encryptionKey: string = process.env
.NEXT_PUBLIC_ENCRYPTION_KEY as string,
) {
const [ivString, encryptedString] = encryptedData.split(":");
if (!encryptedData) return "";
const [ivString, encryptedString] =
encryptedData.split(":");
const iv = Buffer.from(ivString, "hex");
const encrypted = Buffer.from(encryptedString, "hex");
const decipher = crypto.createDecipheriv(
@@ -65,19 +73,35 @@ export function decrypt(
}
const urlKey =
(process.env.NEXT_PUBLIC_ENCRYPTION_KEY as string).slice(0, 16) || "";
(process.env.NEXT_PUBLIC_ENCRYPTION_KEY as string).slice(
0,
16,
) || "";
const urlIV = Buffer.from(urlKey);
export function urlEncrypt(fileId: string): string {
const cipher = crypto.createCipheriv("aes-128-cbc", urlKey, urlIV);
export function shortEncrypt(fileId: string): string {
const cipher = crypto.createCipheriv(
"aes-128-cbc",
urlKey,
urlIV,
);
let cipherText = cipher.update(fileId, "utf8", "hex");
cipherText += cipher.final("hex");
return cipherText;
}
export function urlDecrypt(cipherText: string): string {
const decipher = crypto.createDecipheriv("aes-128-cbc", urlKey, urlIV);
let plainText = decipher.update(cipherText, "hex", "utf8");
export function shortDecrypt(cipherText: string): string {
if (!cipherText) return "";
const decipher = crypto.createDecipheriv(
"aes-128-cbc",
urlKey,
urlIV,
);
let plainText = decipher.update(
cipherText,
"hex",
"utf8",
);
plainText += decipher.final("utf8");
return plainText;
}