-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypt.mjs
31 lines (22 loc) · 923 Bytes
/
crypt.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import crypto from "crypto";
const encryptionKey = process.env.ENCRYPTION_KEY; // crypto.randomBytes(32)
if (encryptionKey == null) {
console.error("Must set ENCRYPTION_KEY environment variable");
process.exit(1);
}
const algorithm = "aes-256-cbc";
export function decrypt(message) {
const [iv, ciphertext] = message.split("--");
const decipher = crypto.createDecipheriv(algorithm, encryptionKey, Buffer.from(iv, "hex"));
let decryptedData = decipher.update(ciphertext, "hex", "utf8");
decryptedData += decipher.final("utf-8");
return JSON.parse(decryptedData);
}
export function encrypt(object) {
const plaintext = JSON.stringify(object);
const iv = crypto.randomBytes(16);
const cipher = crypto.createCipheriv(algorithm, encryptionKey, iv);
let cryptedData = cipher.update(plaintext, "utf8", "hex");
cryptedData += cipher.final("hex");
return `${iv.toString("hex")}--${cryptedData}`;
}