simplify encryption.ts

This commit is contained in:
m5r 2022-05-24 23:13:30 +02:00
parent 8ad21ae9e1
commit b5bb8e1822

View File

@ -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();
}