Skip to content

Instantly share code, notes, and snippets.

@cggaurav
Created February 9, 2019 15:54
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 cggaurav/1de5c0d92e2b900bb0d5f7067cc22e5c to your computer and use it in GitHub Desktop.
Save cggaurav/1de5c0d92e2b900bb0d5f7067cc22e5c to your computer and use it in GitHub Desktop.
(encrypt + decrypt).js
const encrypt = (text, email) => {
const iv = crypto.randomBytes(IV_LENGTH)
const cipher = crypto.createCipheriv('aes-256-cbc', new Buffer(ENCRYPTION_KEY), iv)
let encrypted = cipher.update(text)
encrypted = Buffer.concat([encrypted, cipher.final()])
return `${iv.toString('hex')}:${encrypted.toString('hex')}`
}
const decrypt = (text, email) => {
const textParts = text.split(':')
const iv = new Buffer(textParts.shift(), 'hex')
const encryptedText = new Buffer(textParts.join(':'), 'hex')
const decipher = crypto.createDecipheriv('aes-256-cbc', new Buffer(ENCRYPTION_KEY), iv)
let decrypted = decipher.update(encryptedText)
decrypted = Buffer.concat([decrypted, decipher.final()])
return decrypted.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment