Last active
May 29, 2018 22:02
-
-
Save ashtonmeuser/7def97ad79c2bb8883cdc77fcd0be101 to your computer and use it in GitHub Desktop.
AES-256 encryption and decryption
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 crypto = require('crypto'); | |
| const encryptionSecret = Buffer.from(process.env.ENCRYPTION_SECRET); | |
| const encrypt = (string) => { | |
| const iv = crypto.randomBytes(16); | |
| const cipher = crypto.createCipheriv('aes-256-cbc', encryptionSecret, iv); | |
| let encrypted = cipher.update(string); | |
| encrypted = Buffer.concat([encrypted, cipher.final()]); | |
| return `${iv.toString('hex')}:${encrypted.toString('hex')}`; | |
| }; | |
| function decrypt(string) { | |
| const stringParts = string.split(':'); | |
| const iv = Buffer.from(stringParts.shift(), 'hex'); | |
| const encryptedString = Buffer.from(stringParts.shift(), 'hex'); | |
| const decipher = crypto.createDecipheriv('aes-256-cbc', encryptionSecret, iv); | |
| let decrypted = decipher.update(encryptedString); | |
| decrypted = Buffer.concat([decrypted, decipher.final()]); | |
| return decrypted.toString(); | |
| } | |
| module.exports = { | |
| encrypt, | |
| decrypt, | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment