2022-05-22 00:00:12 +00:00
|
|
|
import crypto from "crypto";
|
|
|
|
|
|
|
|
import serverConfig from "~/config/config.server";
|
|
|
|
|
|
|
|
const ivLength = 16;
|
|
|
|
const algorithm = "aes-256-cbc";
|
2022-05-24 21:13:30 +00:00
|
|
|
const encryptionKey = Buffer.from(serverConfig.app.encryptionKey, "hex");
|
2022-05-22 00:00:12 +00:00
|
|
|
|
|
|
|
export function encrypt(text: string) {
|
|
|
|
const iv = crypto.randomBytes(ivLength);
|
2022-05-24 21:13:30 +00:00
|
|
|
const cipher = crypto.createCipheriv(algorithm, encryptionKey, iv);
|
|
|
|
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
|
2022-05-22 00:00:12 +00:00
|
|
|
|
2022-05-24 21:13:30 +00:00
|
|
|
return `${iv.toString("hex")}:${encrypted.toString("hex")}`;
|
2022-05-22 00:00:12 +00:00
|
|
|
}
|
|
|
|
|
2022-05-24 21:13:30 +00:00
|
|
|
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()]);
|
2022-05-22 00:00:12 +00:00
|
|
|
|
2022-05-24 21:13:30 +00:00
|
|
|
return decrypted.toString();
|
2022-05-22 00:00:12 +00:00
|
|
|
}
|