cairo/lib/services/crypt.service.ts
Dunemask 0fc5f05b6a
Some checks failed
Deploy Edge / deploy-edge (push) Failing after 2s
S3 Repo Backup / s3-repo-backup (push) Failing after 2s
[INIT] Initial Project Structure
2024-08-24 12:41:04 -06:00

37 lines
1.3 KiB
TypeScript

import crypto, { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
export async function generateKeypair() {
return crypto.generateKeyPairSync("rsa", {
modulusLength: 2048,
publicKeyEncoding: { type: "pkcs1", format: "pem" },
privateKeyEncoding: { type: "pkcs1", format: "pem" },
});
}
export async function encrypt(plaintext: string, hexKey: string): Promise<string> {
const key = Buffer.from(hexKey, "hex");
const algorithm = "aes-256-cbc"; // Encryption algorithm
const iv = randomBytes(16); // Initialization vector
const cipher = createCipheriv(algorithm, key, iv);
let encrypted = cipher.update(plaintext, "utf8", "hex");
encrypted += cipher.final("hex");
// Combine IV and encrypted text
return iv.toString("hex") + ":" + encrypted;
}
// Decrypt function
export async function decrypt(encryptedText: string, hexKey: string): Promise<string> {
const key = Buffer.from(hexKey, "hex");
const algorithm = "aes-256-cbc";
const textParts = encryptedText.split(":");
const iv = Buffer.from(textParts[0], "hex");
const encrypted = textParts[1];
const decipher = createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, "hex", "utf8");
decrypted += decipher.final("utf8");
return decrypted;
}