simplify encryption.ts
This commit is contained in:
parent
8ad21ae9e1
commit
b5bb8e1822
@ -4,26 +4,20 @@ import serverConfig from "~/config/config.server";
|
|||||||
|
|
||||||
const ivLength = 16;
|
const ivLength = 16;
|
||||||
const algorithm = "aes-256-cbc";
|
const algorithm = "aes-256-cbc";
|
||||||
const encryptionKey = serverConfig.app.encryptionKey;
|
const encryptionKey = Buffer.from(serverConfig.app.encryptionKey, "hex");
|
||||||
|
|
||||||
export function encrypt(text: string) {
|
export function encrypt(text: string) {
|
||||||
const encryptionKeyAsBuffer = Buffer.isBuffer(encryptionKey) ? encryptionKey : Buffer.from(encryptionKey, "hex");
|
|
||||||
const iv = crypto.randomBytes(ivLength);
|
const iv = crypto.randomBytes(ivLength);
|
||||||
const cipher = crypto.createCipheriv(algorithm, encryptionKeyAsBuffer, iv);
|
const cipher = crypto.createCipheriv(algorithm, encryptionKey, iv);
|
||||||
const encrypted = cipher.update(text);
|
const encrypted = Buffer.concat([cipher.update(text), cipher.final()]);
|
||||||
const encryptedBuffer = Buffer.concat([encrypted, cipher.final()]);
|
|
||||||
|
|
||||||
return `${iv.toString("hex")}:${encryptedBuffer.toString("hex")}`;
|
return `${iv.toString("hex")}:${encrypted.toString("hex")}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function decrypt(encryptedHexText: string) {
|
export function decrypt(encryptedText: string) {
|
||||||
const encryptionKeyAsBuffer = Buffer.isBuffer(encryptionKey) ? encryptionKey : Buffer.from(encryptionKey, "hex");
|
const [iv, encrypted] = encryptedText.split(":").map((hex) => Buffer.from(hex, "hex"));
|
||||||
const [hexIv, hexText] = encryptedHexText.split(":");
|
const decipher = crypto.createDecipheriv(algorithm, encryptionKey, iv);
|
||||||
const iv = Buffer.from(hexIv!, "hex");
|
const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
|
||||||
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()]);
|
|
||||||
|
|
||||||
return decryptedBuffer.toString();
|
return decrypted.toString();
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user