Skip to content

Instantly share code, notes, and snippets.

@kexoth
Created March 20, 2014 00:04
Show Gist options
  • Save kexoth/9654433 to your computer and use it in GitHub Desktop.
Save kexoth/9654433 to your computer and use it in GitHub Desktop.
AES 128 Encryption/Decription with CBC, PKCS7 Padding & Base64 Encoding/Decoding.
var http = require('http');
var url = require('url');
var crypto = require('crypto');
var AESCrypt = {};
AESCrypt.decrypt = function(cryptkey, iv, encryptdata) {
encryptdata = new Buffer(encryptdata, 'base64').toString('binary');
var decipher = crypto.createDecipheriv('aes-128-cbc', cryptkey, iv),
decoded = decipher.update(encryptdata, 'binary', 'utf8');
decoded += decipher.final('utf8');
return decoded;
}
AESCrypt.encrypt = function(cryptkey, iv, cleardata) {
var encipher = crypto.createCipheriv('aes-128-cbc', cryptkey, iv),
encryptdata = encipher.update(cleardata, 'utf8', 'binary');
encryptdata += encipher.final('binary');
encode_encryptdata = new Buffer(encryptdata, 'binary').toString('base64');
return encode_encryptdata;
}
var cryptkey = '55abe029fdebae58',
iv = 'bcb04b7e103a0cde',
buf = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.',
enc = AESCrypt.encrypt(cryptkey, iv, buf);
console.log(enc);
var dec = AESCrypt.decrypt(cryptkey, iv, enc);
console.log(dec);
var server = http.createServer(function (req, res) {
console.log("____________________________");
console.log("URL:", decodeURIComponent(req.url));
console.log("Method: ", req.method);
console.log("Body:", req.body);
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
req.addListener("data", function(data) {
// var base64_string = new Buffer(data, );
var request = new Buffer(data, "binary").toString("utf8");
console.log("Request: ", request);
var dec = AESCrypt.decrypt(cryptkey, iv, request);
console.log("Request Decrypted: ", dec);
res.writeHead(200);
var response = {token:"ad7793bfa02db8d25ca13f37a5ff860b"};
console.log("Response: ", JSON.stringify(response));
var enc = AESCrypt.encrypt(cryptkey, iv, JSON.stringify(response));
console.log("Response Encrypted: ", enc);
res.write(enc, 'binary');
res.end();
});
console.log("QueryString: ", query);
for(var item in req.headers) {
console.log(item + ": " + req.headers[item]);
}
});
server.listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment