Created
November 24, 2021 19:29
-
-
Save rockchalkwushock/757a483c6a8e01cce234a58922fd99d0 to your computer and use it in GitHub Desktop.
Encrypt and decrypt objects in Node
This file contains hidden or 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 { 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