-
-
Save elranu/5fdc98fb0125421be062691037a1220b to your computer and use it in GitHub Desktop.
Stronger Encryption and Decryption in typescript
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'; | |
const ALGORITHM = 'aes-256-cbc'; | |
const ENCODING = 'hex'; | |
const IV_LENGTH = 16; | |
const KEY = process.env.ENCRYPTION_KEY!; | |
export const encrypt = (data: string) => { | |
const iv = crypto.randomBytes(IV_LENGTH); | |
const cipher = crypto.createCipheriv(ALGORITHM, new Buffer(KEY), iv); | |
return Buffer.concat([cipher.update(data,), cipher.final(), iv]).toString(ENCODING); | |
} | |
export const decrypt = (data: string) => { | |
const binaryData = new Buffer(data, ENCODING); | |
const iv = binaryData.slice(-IV_LENGTH); | |
const encryptedData = binaryData.slice(0, binaryData.length - IV_LENGTH); | |
const decipher = crypto.createDecipheriv(ALGORITHM, new Buffer(KEY), iv); | |
return Buffer.concat([decipher.update(encryptedData), decipher.final()]).toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment