encrypt : function(data, key){
algorithm = this.defaultAlgorithm;
format = this.defaultFormat;
var iv = crypto.randomBytes(this.ivLength);
var cipher = crypto.createCipheriv(algorithm, new Buffer(key, 'hex'), iv);
var encrypted = cipher.update(data, 'utf8', format) + cipher.final(format);
//put the vector at the beginning
return iv.toString('hex') + encrypted;
},
decrypt : function(data, key){
algorithm = this.defaultAlgorithm;
format = this.defaultFormat;
var ivLength = this.ivLength * 2;
var iv = new Buffer(data.substring(0, ivLength), 'hex');
//get the vector from the begging of the string, hex is twice length the string
data = data.substring(ivLength);
var decipher = crypto.createDecipheriv(algorithm, new Buffer(key, 'hex'), iv);
var decrypted = decipher.update(data, format, 'utf8') + decipher.final('utf8');
return decrypted;
}
};
Here is the test class
sillcat-aes/test/encryptAndDecrypt.js
require("should");
var crypto = require('crypto');
var AESTool = require("../lib/app");
describe("Encrypt&Decrypt String", function(){
it("should encrypt&decrypt string password", function(){
console.log("");
var key = crypto.randomBytes(32);
var raw_data = "I love nodejs, I used to use javascript for a long time!";
var secret_data = AESTool.encrypt(raw_data, key);
console.log("raw_data is = " + raw_data);
console.log("secret data is = " + secret_data);
var decrypt_data = AESTool.decrypt(secret_data, key);
console.log("decrypt data is= " + decrypt_data);
decrypt_data.should.equal(raw_data);
});
});
3. Build the Test Case
>sudo npm install -g mocha
global install the mocha tool in my local machine.
Then, try to run the test cases like this>
>mocha test/*.js
raw_data is = I love nodejs, I used to use javascript for a long time! secret data is = 39f8bdc4e8087fd4c53195702522db82c5bf60771fedfa765ea8b7d7ea6a69c29f09054a13c1a1e4d1ae52e285ebdc5ea62fe649e64781888626febfc384a3c3c7e306ae319ed586892009fc6596a890 decrypt data is= I love nodejs, I used to use javascript for a long time!
References: AES Encrypt and Decrypt http://blog.csdn.net/searchsun/article/details/2516191 http://nodejs.org/api/crypto.html http://www.360doc.com/content/10/0326/17/229143_20367618.shtml http://snoopyxdy.blog.163.com/blog/static/601174402012730105523656/