Skip to content

Instantly share code, notes, and snippets.

@ruanmartinelli
Created January 19, 2024 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ruanmartinelli/93b3cdf2f318eaf4ce1bd536c772bc5b to your computer and use it in GitHub Desktop.
Save ruanmartinelli/93b3cdf2f318eaf4ce1bd536c772bc5b to your computer and use it in GitHub Desktop.
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