Skip to content

Instantly share code, notes, and snippets.

@mpede
Last active August 29, 2015 14:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpede/b5d83b6068a23c78e5db to your computer and use it in GitHub Desktop.
Save mpede/b5d83b6068a23c78e5db to your computer and use it in GitHub Desktop.
simple AES encryption class for node - you can pass key and iv or it will create them - you can change them after object creation as well
var AES=function(key,iv){
this.rc=function(l){ l=l||16;
var text = "", possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for(var i=0;i<l;i++) text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
this.iv =iv ||this.rc();
this.key=key||this.rc(128);
this.decrypt = function(encryptdata) {
var decipher = crypto.createDecipheriv('aes-256-cbc', crypto.createHash('sha256').update(this.key).digest(), this.iv);
return decipher.update(new Buffer(encryptdata, 'base64').toString('binary'), 'binary', 'utf8')+decipher.final('utf8');
}
this.encrypt = function(cleardata) {
var encipher = crypto.createCipheriv('aes-256-cbc', crypto.createHash('sha256').update(this.key).digest(), this.iv);
return new Buffer(encipher.update(cleardata, 'utf8', 'binary')+encipher.final('binary'), 'binary').toString('base64');
}
};
// test en- and decryption functionality
var AES=new AES();
console.log(AES.encrypt('whole lof of test data'));
console.log(AES.decrypt(AES.encrypt('whole lof of test data')));
// encrypt with fixed key, save IV and data
var AES2=new AES();
AES2.key='my saved key';
var saveText = AES2.iv + AES.encrypt('whole lotta data');
console.log(saveText);
// get IV and data, restore
var AES3= new AES();
AES3.key='my saved key';
AES3.iv =saveText.slice(0,16);
var cleartext= AES.decrypt( saveText.slice(16) );
console.log(cleartext);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment