Advertisement
Guest User

Crypto

a guest
Aug 27th, 2016
137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var http = require('http');
  2. var express = require('express');
  3. var path = require('path');
  4. var cookieParser = require('cookie-parser');
  5. var bodyParser = require('body-parser');
  6. var crypto = require('crypto');
  7.  
  8. var secrets = require('./secrets');
  9.  
  10. var app = express();
  11.  
  12. app.set('views', path.join(__dirname, 'views'));
  13. app.set('view engine', 'ejs');
  14.  
  15. app.use(bodyParser.json());
  16. app.use(bodyParser.urlencoded({ extended: false }));
  17. app.use(cookieParser());
  18.  
  19. console.log("Starting server...");
  20.  
  21. var encrypt = function(data) {
  22.   var cipher = crypto.createCipher('aes-128-ecb', secrets.key);
  23.   cipher.setAutoPadding(true);
  24.   var ctxt = cipher.update(data, 'ascii', 'hex');
  25.   ctxt += cipher.final('hex');
  26.   return ctxt;
  27. };
  28.  
  29. var decrypt = function(data) {
  30.   var decipher = crypto.createDecipher('aes-128-ecb', secrets.key);
  31.   decipher.setAutoPadding(true);
  32.   var ptxt = decipher.update(data, 'hex', 'ascii');
  33.   ptxt += decipher.final('ascii');
  34.   return ptxt;
  35. };
  36.  
  37. app.get('/', function(req, res) {
  38.   if(req.cookies.auth) {
  39.     var auth = decrypt(req.cookies.auth);
  40.     auth = JSON.parse(auth);
  41.     res.render('index', {auth: auth, flag: secrets.flag});
  42.   }
  43.   else {
  44.     res.render('index', {auth: false});
  45.   }
  46. });
  47.  
  48. app.post('/logout', function(req, res) {
  49.   res.append('Set-Cookie', 'auth=; Path=/; HttpOnly');
  50.   res.redirect('/');
  51. });
  52.  
  53. app.post('/login', function(req, res) {
  54.   if(req.body.username && req.body.password && !req.body.admin) {
  55.     if(req.body.username===secrets.username && req.body.password===secrets.password) {
  56.       req.body.admin = true;
  57.     }
  58.     auth = JSON.stringify(req.body);
  59.     auth = encrypt(auth);
  60.     res.append('Set-Cookie', 'auth='+auth+'; Path=/; HttpOnly');
  61.   }
  62.   res.redirect('/');
  63. });
  64.  
  65. // catch 404
  66. app.use(function(req, res, next) {
  67.   var err = new Error('Not Found');
  68.   err.status = 404;
  69.   next(err);
  70. });
  71.  
  72. // error handler
  73. app.use(function(err, req, res, next) {
  74.   console.log(err);
  75.   res.status(err.status || 500);
  76.   res.render('error', {
  77.     status: err.status
  78.   });
  79. });
  80.  
  81. var server = http.createServer(app).listen(3000, function(){
  82.   console.log("HTTP server listening on port 3000!");
  83. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement