Skip to content

Instantly share code, notes, and snippets.

@marshallswain
Created June 29, 2017 19:47
Show Gist options
  • Save marshallswain/59bfd5f76e8c13f3b2e260b1223187a8 to your computer and use it in GitHub Desktop.
Save marshallswain/59bfd5f76e8c13f3b2e260b1223187a8 to your computer and use it in GitHub Desktop.
Encrypt with Initialization Vector
const crypto = require('crypto')
const { Buffer } = require('buffer')
const IV_LENGTH = 16 // For AES, this is always 16
function encrypt (text, key) {
let iv = crypto.randomBytes(IV_LENGTH)
let cipher = crypto.createCipheriv('aes-256-cbc', Buffer.from(key), iv)
let encrypted = cipher.update(text)
encrypted = Buffer.concat([encrypted, cipher.final()])
return iv.toString('hex') + ':' + encrypted.toString('hex')
}
function decrypt (text, key) {
let textParts = text.split(':')
let iv = Buffer.from(textParts.shift(), 'hex')
let encryptedText = Buffer.from(textParts.join(':'), 'hex')
let decipher = crypto.createDecipheriv('aes-256-cbc', Buffer.from(key), iv)
let decrypted = decipher.update(encryptedText)
decrypted = Buffer.concat([decrypted, decipher.final()])
return decrypted.toString()
}
module.exports = { decrypt, encrypt }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment