Last active
August 29, 2015 14:08
-
-
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
This file contains 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
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'); | |
} | |
}; |
This file contains 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
// 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