Last active
August 20, 2022 00:29
-
-
Save flybayer/1e0642ac50b5bcebd74d2982e3bd033a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import crypto from "crypto" | |
import {assert} from "../utils" | |
export interface EncryptedString { | |
data: string | |
iv: string | |
} | |
export class Crypto { | |
static decrypt(text: string): string { | |
const ALGORITHM = "aes-256-ctr" | |
const splitText = text.split(":") | |
assert(splitText[0], "Missing first part of encrypted value") | |
assert(splitText[1], "Missing second part of encrypted value") | |
const iv = Buffer.from(splitText[0], "hex") | |
const encryptionKey = process.env.DATA_ENCRYPTION_KEY | |
const encryptedText = Buffer.from(splitText[1], "hex") | |
const decipher = crypto.createDecipheriv(ALGORITHM, Buffer.from(encryptionKey, "hex"), iv) | |
let decrypted = decipher.update(encryptedText) | |
decrypted = Buffer.concat([decrypted, decipher.final()]) | |
return decrypted.toString() | |
} | |
static encrypt(text: string): string { | |
const ALGORITHM = "aes-256-ctr" | |
const iv = crypto.randomBytes(16) | |
const encryptionKey = process.env.DATA_ENCRYPTION_KEY | |
const cipher = crypto.createCipheriv(ALGORITHM, Buffer.from(encryptionKey, "hex"), iv) | |
let encrypted = cipher.update(text) | |
encrypted = Buffer.concat([encrypted, cipher.final()]) | |
return `${iv.toString("hex")}:${encrypted.toString("hex")}` | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment