Created
January 22, 2019 16:42
-
-
Save fijimunkii/0fd5ac7ea99deee92cb68c53c3daf344 to your computer and use it in GitHub Desktop.
encrypt and decrypt with initialization vector
This file contains 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
// encrypt and decrypt with initialization vector | |
// http://vancelucas.com/blog/stronger-encryption-and-decryption-in-node-js/ | |
const crypto = require('crypto'); | |
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY; // Must be 256 bits (32 characters) | |
const IV_LENGTH = 16; // For AES, this is always 16 | |
function encrypt(text) { | |
let iv = crypto.randomBytes(IV_LENGTH); | |
let cipher = crypto.createCipheriv('aes-256-cbc', new Buffer.from(ENCRYPTION_KEY), iv); | |
let encrypted = cipher.update(text); | |
encrypted = Buffer.concat([encrypted, cipher.final()]); | |
return iv.toString('hex') + ':' + encrypted.toString('hex'); | |
} | |
function decrypt(text) { | |
let textParts = text.split(':'); | |
let iv = new Buffer.from(textParts.shift(), 'hex'); | |
let encryptedText = new Buffer.from(textParts.join(':'), 'hex'); | |
let decipher = crypto.createDecipheriv('aes-256-cbc', new Buffer.from(ENCRYPTION_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