Created
January 19, 2024 21:37
-
-
Save ruanmartinelli/93b3cdf2f318eaf4ce1bd536c772bc5b 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' | |
const algorithm = 'aes-192-cbc' | |
const key = crypto.scryptSync('YOUR KEY', 'salt', 24) | |
export function encrypt(text: string) { | |
const iv = crypto.randomBytes(16) | |
const cipher = crypto.createCipheriv(algorithm, key, iv) | |
const encrypted = cipher.update(text, 'utf8', 'hex') | |
return [encrypted + cipher.final('hex'), Buffer.from(iv).toString('hex')].join('|') | |
} | |
export function decrypt(text: string) { | |
const [encrypted, iv] = text.split('|') | |
if (!iv) throw new Error('IV not found') | |
const decipher = crypto.createDecipheriv(algorithm, key, Buffer.from(iv, 'hex')) | |
return decipher.update(encrypted, 'hex', 'utf8') + decipher.final('utf8') | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment