Created
May 1, 2021 18:50
-
-
Save donchev7/0a96280cd93a496b6f56910d9c53fa65 to your computer and use it in GitHub Desktop.
encrypt - decrypt typescript using NodeJS
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 { OPENSSL_VERSION_NUMBER } from 'constants' | |
import crypto from 'crypto' | |
import * as env from 'env-var' | |
const ivSize = 16 | |
const algorithm = 'aes256' | |
// Check for Heartbleed vulnerabilities | |
if (OPENSSL_VERSION_NUMBER <= 268443727) { | |
throw new Error('OpenSSL Version too old') | |
} | |
const encrypt = (plaintext: string, encryptionKey?: string) => { | |
const key = | |
encryptionKey ?? | |
env | |
.get('USER_ENCRYPTION_KEY') | |
.required() | |
.asString() | |
const iv = crypto.randomBytes(ivSize) | |
const cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv) | |
let encrypted = cipher.update(plaintext, 'utf8', 'hex') | |
encrypted += cipher.final('hex') | |
return iv.toString('hex') + encrypted | |
} | |
const decrypt = (encrypted: string, encryptionKey?: string) => { | |
const key = | |
encryptionKey ?? | |
env | |
.get('USER_ENCRYPTION_KEY') | |
.required() | |
.asString() | |
const iv = Buffer.from(encrypted.substring(0, 2 * ivSize), 'hex') | |
const decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv) | |
let decrypted = decipher.update(encrypted.substring(2 * ivSize), 'hex') | |
decrypted = Buffer.concat([decrypted, decipher.final()]) | |
return decrypted.toString('utf8') | |
} | |
const compare = (encrypted: string, plaintext: string) => decrypt(encrypted) === plaintext | |
export { compare, decrypt, encrypt } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment