-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (77 loc) · 2.16 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const express = require("express");
const exphbs = require("express-handlebars");
const app = express();
const path = require("path");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const crypto = require("crypto");
const port = 3000;
const db = [];
const algorithm = "aes-256-cbc";
const key = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);
const encrypt = password => {
let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
let encrypted = cipher.update(password);
encrypted = Buffer.concat([encrypted, cipher.final()]);
return { iv: iv.toString("hex"), encryptedData: encrypted.toString("hex") };
};
const decrypt = (word, iv) => {
let new_iv = Buffer.from(savedIV, "hex");
let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), new_iv);
let deciphered = decipher.update(word);
deciphered = Buffer.concat([deciphered, decipher.final()]);
return deciphered.toString();
};
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(__dirname, "public/images")));
app.use(cookieParser());
app.engine(
"hbs",
exphbs({
extname: ".hbs"
})
);
app.set("view engine", "hbs");
app.get("/", (req, res) => {
res.render("home");
});
app.get("/encrypt", (req, res) => {
res.render("encrypt");
});
app.get("/decrypt", (req, res) => {
res.render("decrypt");
});
app.post("/encrypt", (req, res) => {
const { password } = req.body;
if (password && password.length >= 1) {
const output = encrypt(password);
savedIV = output.iv;
res.render("output", {
message: output.encryptedData
});
} else {
res.render("failure", {
message: "Sorry, something went wrong."
});
}
});
app.post("/decrypt", (req, res, err) => {
const { password } = req.body;
if (err) {
res.render("failure", {
message: "Sorry, something went wrong"
});
} else {
if (password) {
const unhashedPassword = decrypt(password);
res.render("output", {
message: unhashedPassword
});
}
}
});
app.listen(port, () => {
console.log("server is running");
});