Skip to content

Instantly share code, notes, and snippets.

@flybayer
Last active August 20, 2022 00:29
Show Gist options
  • Save flybayer/1e0642ac50b5bcebd74d2982e3bd033a to your computer and use it in GitHub Desktop.
Save flybayer/1e0642ac50b5bcebd74d2982e3bd033a to your computer and use it in GitHub Desktop.
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