From b5bb8e1822947f96e6aecd01d5a1f6e5532d9901 Mon Sep 17 00:00:00 2001 From: m5r Date: Tue, 24 May 2022 23:13:30 +0200 Subject: [PATCH] simplify encryption.ts --- app/utils/encryption.ts | 24 +++++++++--------------- 1 file changed, 9 insertions(+), 15 deletions(-) diff --git a/app/utils/encryption.ts b/app/utils/encryption.ts index 6852e0d..0f484d7 100644 --- a/app/utils/encryption.ts +++ b/app/utils/encryption.ts @@ -4,26 +4,20 @@ import serverConfig from "~/config/config.server"; const ivLength = 16; const algorithm = "aes-256-cbc"; -const encryptionKey = serverConfig.app.encryptionKey; +const encryptionKey = Buffer.from(serverConfig.app.encryptionKey, "hex"); export function encrypt(text: string) { - const encryptionKeyAsBuffer = Buffer.isBuffer(encryptionKey) ? encryptionKey : Buffer.from(encryptionKey, "hex"); const iv = crypto.randomBytes(ivLength); - const cipher = crypto.createCipheriv(algorithm, encryptionKeyAsBuffer, iv); - const encrypted = cipher.update(text); - const encryptedBuffer = Buffer.concat([encrypted, cipher.final()]); + const cipher = crypto.createCipheriv(algorithm, encryptionKey, iv); + const encrypted = Buffer.concat([cipher.update(text), cipher.final()]); - return `${iv.toString("hex")}:${encryptedBuffer.toString("hex")}`; + return `${iv.toString("hex")}:${encrypted.toString("hex")}`; } -export function decrypt(encryptedHexText: string) { - const encryptionKeyAsBuffer = Buffer.isBuffer(encryptionKey) ? encryptionKey : Buffer.from(encryptionKey, "hex"); - const [hexIv, hexText] = encryptedHexText.split(":"); - const iv = Buffer.from(hexIv!, "hex"); - const encryptedText = Buffer.from(hexText!, "hex"); - const decipher = crypto.createDecipheriv(algorithm, encryptionKeyAsBuffer, iv); - const decrypted = decipher.update(encryptedText); - const decryptedBuffer = Buffer.concat([decrypted, decipher.final()]); +export function decrypt(encryptedText: string) { + const [iv, encrypted] = encryptedText.split(":").map((hex) => Buffer.from(hex, "hex")); + const decipher = crypto.createDecipheriv(algorithm, encryptionKey, iv); + const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]); - return decryptedBuffer.toString(); + return decrypted.toString(); }