mirror of
https://github.com/ZeppelinBot/Zeppelin.git
synced 2025-05-10 20:35:02 +00:00
Encrypt message data at rest
This commit is contained in:
parent
3f3d6af4ed
commit
baa3a5640e
10 changed files with 121 additions and 3 deletions
10
backend/src/utils/crypt.test.ts
Normal file
10
backend/src/utils/crypt.test.ts
Normal file
|
@ -0,0 +1,10 @@
|
|||
import test from "ava";
|
||||
|
||||
import { encrypt, decrypt } from "./crypt";
|
||||
|
||||
test("encrypt() followed by decrypt()", t => {
|
||||
const original = "banana 123 👀 💕"; // Includes emojis to verify utf8 stuff works
|
||||
const encrypted = encrypt(original);
|
||||
const decrypted = decrypt(encrypted);
|
||||
t.is(decrypted, original);
|
||||
});
|
35
backend/src/utils/crypt.ts
Normal file
35
backend/src/utils/crypt.ts
Normal file
|
@ -0,0 +1,35 @@
|
|||
import "../loadEnv";
|
||||
|
||||
import crypto, { DecipherGCM } from "crypto";
|
||||
|
||||
if (!process.env.KEY) {
|
||||
// tslint:disable-next-line:no-console
|
||||
console.error("Environment value KEY required for encryption");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const KEY = process.env.KEY;
|
||||
const ALGORITHM = "aes-256-gcm";
|
||||
|
||||
export function encrypt(str) {
|
||||
// Based on https://gist.github.com/rjz/15baffeab434b8125ca4d783f4116d81
|
||||
|
||||
const iv = crypto.randomBytes(16);
|
||||
const cipher = crypto.createCipheriv(ALGORITHM, KEY, iv);
|
||||
|
||||
let encrypted = cipher.update(str, "utf8", "base64");
|
||||
encrypted += cipher.final("base64");
|
||||
return `${iv.toString("base64")}.${cipher.getAuthTag().toString("base64")}.${encrypted}`;
|
||||
}
|
||||
|
||||
export function decrypt(encrypted) {
|
||||
// Based on https://gist.github.com/rjz/15baffeab434b8125ca4d783f4116d81
|
||||
|
||||
const [iv, authTag, encryptedStr] = encrypted.split(".");
|
||||
const decipher = crypto.createDecipheriv(ALGORITHM, KEY, Buffer.from(iv, "base64"));
|
||||
decipher.setAuthTag(Buffer.from(authTag, "base64"));
|
||||
|
||||
let decrypted = decipher.update(encryptedStr, "base64", "utf8");
|
||||
decrypted += decipher.final("utf8");
|
||||
return decrypted;
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue