-
-
Save eldorplus/c77abfbed6f3f7265aca3eba53bf0ce3 to your computer and use it in GitHub Desktop.
AES encryption example for Node.js
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
| /** | |
| * Created by Awesometic | |
| * references: https://gist.github.com/ericchen/3081970 | |
| * This source is updated example code of above source code. | |
| * I added it two functions that are make random IV and make random 256 bit key. | |
| * It's encrypt returns Base64 encoded cipher, and also decrpyt for Base64 encoded Cipher | |
| */ | |
| var crypto = require('crypto'); | |
| var AESCrypt = {}; | |
| AESCrypt.encrypt = function(cryptKey, crpytIv, plainData) { | |
| var encipher = crypto.createCipheriv('aes-256-cbc', cryptKey, crpytIv), | |
| encrypted = encipher.update(plainData, 'utf8', 'binary'); | |
| encrypted += encipher.final('binary'); | |
| return new Buffer(encrypted, 'binary').toString('base64'); | |
| }; | |
| AESCrypt.decrypt = function(cryptKey, cryptIv, encrypted) { | |
| encrypted = new Buffer(encrypted, 'base64').toString('binary'); | |
| var decipher = crypto.createDecipheriv('aes-256-cbc', cryptKey, cryptIv), | |
| decrypted = decipher.update(encrypted, 'binary', 'utf8'); | |
| decrypted += decipher.final('utf8'); | |
| return decrypted; | |
| }; | |
| AESCrypt.makeIv = crypto.randomBytes(16); | |
| // Change this private symmetric key salt | |
| AESCrypt.KEY = crypto.createHash('sha256').update('Awesometic').digest(); | |
| module.exports = AESCrypt; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment