Skip to content

Instantly share code, notes, and snippets.

@awesometic
Last active February 1, 2021 01:22
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save awesometic/b3cbf0dbf4c2beb19ed2ebdbe31c40ba to your computer and use it in GitHub Desktop.
Save awesometic/b3cbf0dbf4c2beb19ed2ebdbe31c40ba to your computer and use it in GitHub Desktop.
AES encryption example for Node.js
/**
* 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;
@mollthecoder
Copy link

Please leave instructions on how to use it

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment