Created
December 28, 2018 10:53
-
-
Save cggaurav/77c78613c24aad0b1905469290d0f3e4 to your computer and use it in GitHub Desktop.
Encrypt + Decrypt 101 with aes-256-cbc
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
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