Skip to content

Instantly share code, notes, and snippets.

@rockchalkwushock
Created November 24, 2021 19:29
Show Gist options
  • Save rockchalkwushock/757a483c6a8e01cce234a58922fd99d0 to your computer and use it in GitHub Desktop.
Save rockchalkwushock/757a483c6a8e01cce234a58922fd99d0 to your computer and use it in GitHub Desktop.
Encrypt and decrypt objects in Node
import { createCipheriv, createDecipheriv, randomBytes } from 'crypto'
const iv = randomBytes(process.env.RANDOM_INTEGER)
const cipher = createCipheriv(process.env.ALGORITHM, process.env.SECRET_KEY, iv)
export const encrypt = (object) => {
const encrypted = Buffer.concat([cipher.update(JSON.stringify(object)), cipher.final()]);
return {
content: encrypted.toString('hex'),
iv: iv.toString('hex'),
}
export const decrypt = (hash) => {
const decipher = createDecipheriv(process.env.ALGORITHM, process.env.SECRET_KEY, Buffer.from(hash.iv, 'hex'));
const decrypted = Buffer.concat([decipher.update(Buffer.from(hash.content, 'hex')), decipher.final()]);
return JSON.parse(decrypted.toString())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment