2021-07-31 15:57:43 +00:00
|
|
|
import crypto from "crypto";
|
|
|
|
import { getConfig } from "blitz";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
const { serverRuntimeConfig } = getConfig();
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
const IV_LENGTH = 16;
|
|
|
|
const ALGORITHM = "aes-256-cbc";
|
2021-07-31 14:33:18 +00:00
|
|
|
|
|
|
|
export function encrypt(text: string, encryptionKey: Buffer | string) {
|
2021-08-01 14:03:49 +00:00
|
|
|
const encryptionKeyAsBuffer = Buffer.isBuffer(encryptionKey) ? encryptionKey : Buffer.from(encryptionKey, "hex");
|
2021-07-31 15:57:43 +00:00
|
|
|
const iv = crypto.randomBytes(IV_LENGTH);
|
|
|
|
const cipher = crypto.createCipheriv(ALGORITHM, encryptionKeyAsBuffer, iv);
|
|
|
|
const encrypted = cipher.update(text);
|
|
|
|
const encryptedBuffer = Buffer.concat([encrypted, cipher.final()]);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
return `${iv.toString("hex")}:${encryptedBuffer.toString("hex")}`;
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function decrypt(encryptedHexText: string, encryptionKey: Buffer | string) {
|
2021-08-01 14:03:49 +00:00
|
|
|
const encryptionKeyAsBuffer = Buffer.isBuffer(encryptionKey) ? encryptionKey : Buffer.from(encryptionKey, "hex");
|
2021-07-31 15:57:43 +00:00
|
|
|
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()]);
|
2021-07-31 14:33:18 +00:00
|
|
|
|
2021-07-31 15:57:43 +00:00
|
|
|
return decryptedBuffer.toString();
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export function computeEncryptionKey(userIdentifier: string) {
|
2021-07-31 15:57:43 +00:00
|
|
|
return crypto.scryptSync(userIdentifier, serverRuntimeConfig.masterEncryptionKey, 32);
|
2021-07-31 14:33:18 +00:00
|
|
|
}
|