Commit 476f734c authored by Frauke's avatar Frauke
Browse files

Added node2 and created and saved encrypted message and sessionkey

parent bdec7549
......@@ -5,8 +5,10 @@
"main": "./server/server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "nodemon",
"start": "node ./server/server.js"
"watch": "nodemon ./server/server.js",
"start": "node ./server/server.js",
"watch2": "nodemon ./server2/server.js",
"start2": "node ./server2/server.js"
},
"repository": {
"type": "git",
......
......@@ -12,6 +12,11 @@
<form action="logout" id="logout">
<input type="submit" value="Log out">
</form>
<form action="send" id="send">
<textarea name="message" rows="8" cols="80" id="message"></textarea>
<input type="submit" value="Send message">
</form>
<script src="js/vendor/OpenCrypto.js"></script>
<script src="js/logout.js"></script>
</body>
......
This diff is collapsed.
......@@ -17,6 +17,17 @@ app.use(bodyParser.raw())
app.use(bodyParser.urlencoded({extended: false}))
app.use(passport.initialize())
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8181')
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST')
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
next()
})
// private path which needs authentication
app.get('/hello', passport.authenticate('jwt-strategy', { failureRedirect: '/sign-in', session: false }), (req, res) => {
res.status(200).send('Hello')
......
{"salt":"0624d8cb0b653da6094e65cc3020517e","privateKey":"-----BEGIN ENCRYPTED PRIVATE KEY-----\r\nMIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQ3wkNZgyS1F+R6vYn\r\nA4xhrgIC+gAwDAYIKoZIhvcNAgsFADAdBglghkgBZQMEASoEECPLmRI75C46MLbE\r\nuxMq/T4EggTQUa7soMjCEGhxlw8L4ny1ND6+C58C7JxstzOPC15fBW5QNghRCx36\r\nZodf9ByzXGBkbU9uVtoiCB7LlCZ9geZU80FYrdZ2pMozglmkrJ+pzO5ysXZIV+uv\r\nHNWFsksY6Jx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KLo/Q24ego4RVdwxeYsU1CXiPP5f/RwjK8SWMVCCJrOyBFLI3jAKcYaaHp\r\nxRuz+ZYmZvmR2EE2Iaqa2iFOUS4yiAjpXYubIOALA763WmzNUW7lU6EjWOLl7fDi\r\nm330saay7mNsg3T5k9fPwlXR8/HuSVAcXiA8rkiAtcJFZwajekaPKRQ6U1aog/H+\r\n5k0if//3B9BISaGdnVQ8SMAdy+247X4aM3Atc7CRk7o6BPaa1uS5l8xcnKymb3Oo\r\nzFpvY05O3sTJ5VO9C1yjnvQCf8x2p4sFdBjO4oDoa85pi8BO3SjTkJ/iFlfOlF6p\r\nsUKHbMNidMkbJAG+bbSjXordipdTFGePlBeZEo+WL0lTHTBZjZxI/uGwTFf9HHIi\r\n5+cbytTOaZC5vMbxGAWtHsQs6cc66Dvvsoj6cNK6RlUH66YaJ4+XBCFZatmdmT+D\r\nf3B0/eoXtK3V82H3pXlG+blDf41lGoDfrkimeZmG+u5xFJjmx9uFmoE=\r\n-----END ENCRYPTED PRIVATE KEY-----"}
\ No newline at end of file
{"publicKey":"-----BEGIN PUBLIC KEY-----\r\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiaGLxrmtcwNkCgtnkGyS\r\n0Ph9HCGbFEQpX7AC7mzdpGV49acSjjfgIetUxiUH4le3vLLsxyYHIp7m09otBbuJ\r\nwQ2gbQX17poJ6bQsOf9LSpIkgt/SfVHhjcyZZIXf4B3YnahcH1kH0B901uG0hzzq\r\nvltZFeJRrufQdIfVnZAC57KkGPjBXBHjhnLeKBdMfm8fCA5BWkFomxQMP3qXXQ7W\r\nkeHRWuh++RExhL9XwMJCWR7cf25ZX+eNEcubaPJefml3+MdwVn7lzT0/j6F5xi+x\r\nUxSkAMI/H+XvmEy+ipOl8jp1VxTqxBJC/ZPAQcfw0bEVay/wVd2LKsqr5sFXx94A\r\n/wIDAQAB\r\n-----END PUBLIC KEY-----"}
\ No newline at end of file
ucfUm1FZenEX/tcoaM05HJXdYafbBFoIjSsikfqtp8Rrgg==
\ No newline at end of file
dcMS0MRQLStSNjER+y2CrRMNhI4Jrx8VxjEj9upty12Hb9B887A0wtNduYRZDLcY1YTRpK/RF+tr5b7kry5PNGwrnCpa7b80hxDEzBb9NGT4bQonhEoduS07Sv7P6v/GvfLYCbGLfzXROJn03h1wK9IVWEwhEoitGa1QPBb8PDyJ+3uiNcW4iUMla54+Yz9YC/SGPzJy5TqAG3r6m71DPMAO8zL9h3L43Tni44ZPAblfCgqMb1z/1mb0eYU6H8gU+evyYkHFiUrwz0CSLMOBsDdcM4EV2j4nuFmKnEakBmToqqWRpx5UIdi/7TJSXsA4sFcJQYD1ODhomjLtR1uNEw==
\ No newline at end of file
{"salt":"0624d8cb0b653da6094e65cc3020517e","privateKey":"-----BEGIN ENCRYPTED PRIVATE KEY-----\r\nMIIFNTBfBgkqhkiG9w0BBQ0wUjAxBgkqhkiG9w0BBQwwJAQQVdzHbjAJ+ngZI8wN\r\nn5IJcAIC+gAwDAYIKoZIhvcNAgsFADAdBglghkgBZQMEASoEEDx8NfzwPvE5uDUz\r\nkRZiea4EggTQ5S5PvTdM4+J6BzXmxW/l7V1lYRf1Eyts8TP2Vc6crrKPJw1Adwhp\r\nr8mfS8k0yDR5DzomSAbBb+6Q1fw9B7aJKCYzuRs6MXoBPSMk3CQHBY0m5sJAqhuG\r\ntatHLW+PbhHuSPhtN/cSR9h0rTrU4BoQs+INgbukg0O/qBu6u+0hquo8Srg+aAS3\r\n+nOuJOypPsb+0wx2CvWNxtTZ8zHKd2Kv4zY0CHi11vd755ebTfc+qL0DOOAZCjet\r\nBEuCdJjeGhR9uCBEYVBKZFswgA1FTPs45H487JlW7cBoXqRHO+uQ2tiVMDfD+FjH\r\nUBBGs0zKFhinSp65Fai+7oEYse3wU4I9blH9NTEwXNwm3E8qPOWuNWC2ywIHA1Nq\r\nFAysjl3WLJA0TNxoRxCmcqh23FqIo0b1Zyq1hZBdIcP7uh2vtDF0NgONRxaeisr4\r\nC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q86OrACpY\r\nFCNYW7cXQT8NxJBTetmZUFbzY+7X2+T5TtuTlyFP3/DeYTRN+YiCUKLAmoP+x+ka\r\nQXVTjaR355HhMGreU3VYn7zgBywmJ/ncKlKkI9fJ+dTvVG6nLMRkBkf+1gIXbAJe\r\npehy06ujj0rRRuCRDiy1JTILG8FBaYbR6YXU1gX8JdCKmAgGO2PQYg0=\r\n-----END ENCRYPTED PRIVATE KEY-----"}
\ No newline at end of file
{"publicKey":"-----BEGIN PUBLIC KEY-----\r\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqr7suxdnXQOGVU+lB6mI\r\nXrGUFuYgkGovB51M/jLcM4w182ErnOEN1d9Bp/BssNRNWDLovwSDdIv6cyPGurFK\r\n87z11TLGKORdBhu54aGVFh55ljNDd1iUx1lm9JAzpJfVkanL7xFl1wGtIAYjIlyw\r\n27pPjoGNRuJEU/TJP1f9/e5TfqxKFBt21yemg4Yp3Hsfz0KHZ7JtUcD6VnYg+ZE7\r\nnoSaGaR2R8v/mCHolO2O/cnjR0/VQiUhN0gFFkjThXWud6Kx7gIVRUseChbc8doL\r\nupSHyOgbda3dqhhG2cePDo/uDXhDrnji1kua64kTiP3BaWF59e3TR0JirzddXpVE\r\ndQIDAQAB\r\n-----END PUBLIC KEY-----"}
\ No newline at end of file
const express = require('express')
const app = express()
const path = require('path')
const bodyParser = require('body-parser')
const crypto = require('crypto')
const jwt = require('jsonwebtoken')
const passport = require('passport')
const fileUtils = require('./utils/fileUtils')
const passportUtils = require('./utils/passportStrategy.js')(app)
var nonce
// Add headers
app.use(function (req, res, next) {
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080')
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type')
next()
})
app.use(express.static(path.join(__dirname, '../public')))
app.use(bodyParser.json())
app.use(bodyParser.raw())
app.use(bodyParser.urlencoded({extended: false}))
app.use(passport.initialize())
// private path which needs authentication
app.get('/hello', passport.authenticate('jwt-strategy', { failureRedirect: '/sign-in', session: false }), (req, res) => {
res.status(200).send('Hello')
})
app.get('/sign-in', (req, res) => {
res.status(200).sendFile(path.join(__dirname, '../public/sign-in.html'))
})
app.post('/sign-in', (req, res) => {
fileUtils.readFile('./server2/files/signpublickey.json').then((data) => {
data = JSON.parse(data)
const verify = crypto.createVerify('SHA512')
verify.update(nonce)
if (verify.verify(data.publicKey, req.body)) {
// creaye secret to create JWT
// TODO: save on server
crypto.randomBytes(256, (err, buf) => {
if (err) {
res.status(500).send('Ooops, something went wrong')
console.log(err)
}
app.set('tokenSecret', buf)
const token = jwt.sign({text: 'test'}, buf)
res.status(200).send(token)
})
} else {
res.status(401).send('Login denied!')
}
}).catch((err) => {
res.status(500).send('Ooops, something went wrong')
console.log(err)
})
})
app.get('/register', (req, res) => {
res.status(200).sendFile(path.join(__dirname, '../public/register.html'))
})
app.post('/register', (req, res) => {
const encryptPublicKey = JSON.stringify({publicKey: req.body.encryptPublicKey})
const encryptPrivateKeySalt = JSON.stringify({salt: req.body.salt, privateKey: req.body.encryptPrivateKey})
const signPublicKey = JSON.stringify({publicKey: req.body.signPublicKey})
const signPrivateKeySalt = JSON.stringify({salt: req.body.salt, privateKey: req.body.signPrivateKey})
// Save keys & salt to files
const pathName = './server2/files/'
const writeEncryptPublicKey = fileUtils.writeFile('encryptpublickey.json', encryptPublicKey, pathName)
const writeEncryptPrivateKeySalt = fileUtils.writeFile('encryptprivatekey.json', encryptPrivateKeySalt, pathName)
const writeSignPublicKey = fileUtils.writeFile('signpublickey.json', signPublicKey, pathName)
const writeSignPrivateKeySalt = fileUtils.writeFile('signprivatekey.json', signPrivateKeySalt, pathName)
Promise.all([writeEncryptPublicKey, writeEncryptPrivateKeySalt, writeSignPublicKey, writeSignPrivateKeySalt]).then(() => {
res.status(200).end()
}).catch((er) => {
console.log(er)
res.status(500).send('Ooops, something went wrong')
})
})
app.get('/encryptpublickey', (req, res) => {
fileUtils.readFile('./server2/files/encryptpublickey.json').then((data) => {
data = JSON.parse(data)
res.status(200).send(data)
}).catch((err) => {
res.status(500).send('Ooops, something went wrong')
console.log(err)
})
})
app.get('/encryptprivatekey', (req, res) => {
fileUtils.readFile('./server2/files/encryptprivatekey.json').then((data) => {
data = JSON.parse(data)
res.status(200).send(data)
}).catch((err) => {
res.status(500).send('Ooops, something went wrong')
console.log(err)
})
})
app.get('/signpublickey', (req, res) => {
fileUtils.readFile('./server2/files/signpublickey.json').then((data) => {
data = JSON.parse(data)
res.status(200).send(data)
}).catch((err) => {
res.status(500).send('Ooops, something went wrong')
console.log(err)
})
})
app.get('/signprivatekey', (req, res) => {
fileUtils.readFile('./server2/files/signprivatekey.json').then((data) => {
data = JSON.parse(data)
res.status(200).send(data)
}).catch((err) => {
res.status(500).send('Ooops, something went wrong')
console.log(err)
})
})
app.get('/nonce', (req, res) => {
crypto.randomBytes(256, (err, buf) => {
if (err) {
res.status(500).send('Ooops, something went wrong')
console.log(err)
}
nonce = buf
res.status(200).send(nonce)
})
})
app.post('/send', (req, res) => {
// Save sessionKey and message
const pathName = './server2/files/'
const writeSessionKey = fileUtils.writeFile('sessionkey.json', req.body.sessionKey, pathName)
const writeMessage = fileUtils.writeFile('message.json', req.body.message, pathName)
Promise.all([writeSessionKey, writeMessage]).then(() => {
res.status(200).end()
}).catch((er) => {
console.log(er)
res.status(500).send('Ooops, something went wrong')
})
})
app.listen(8181)
const fs = require('fs')
const path = require('path')
// Writes a string to the filesystem.
function writeFile (fileName, value, pathName) {
return new Promise((resolve, reject) => {
makeDir(pathName).then(() => {
fs.writeFile(path.join(pathName, fileName), value, (err) => {
if (err) {
reject(err)
}
resolve()
})
})
})
}
// Creates a dir on the filesystem if it does not exist.
function makeDir (pathName) {
return new Promise((resolve, reject) => {
if (!fs.existsSync(pathName)) {
fs.mkdir(pathName, (err) => {
if (err) {
reject(err)
}
resolve()
})
} else {
resolve()
}
})
}
// Reads a file from the filesystem.
function readFile (fileName) {
return new Promise((resolve, reject) => {
fs.readFile(fileName, 'utf8', (err, data) => {
if (err) {
reject(err)
}
resolve(data)
})
})
}
module.exports = {
writeFile,
readFile
}
const passport = require('passport')
const CustomStrategy = require('passport-custom')
const jwt = require('jsonwebtoken')
module.exports = function (app) {
passport.use('jwt-strategy', new CustomStrategy(
function (req, done) {
const cookie = decodeURIComponent(req.headers.cookie)
console.log(cookie)
if (cookie) {
const jwtToken = getCookie(cookie, 'access_token')
if (app.get('tokenSecret')) {
jwt.verify(jwtToken, app.get('tokenSecret'), function (err, decoded) {
if (err) {
done(err, false, {message: 'Access denied'})
} else {
done(null, decoded)
}
})
} else {
done(null, false, {message: 'Access denied'})
}
} else {
done(null, false, {message: 'Access denied'})
}
}
))
}
function getCookie (decodedCookie, cname) {
const name = cname + '='
const ca = decodedCookie.split(';')
for (let i = 0; i < ca.length; i++) {
let c = ca[i]
while (c.charAt(0) === ' ') {
c = c.substring(1)
}
if (c.indexOf(name) === 0) {
return c.substring(name.length, c.length)
}
}
return ''
}
const indexedDB = require('./indexedDB')
const crypt = new OpenCrypto()
const axios = require('axios')
const form = document.getElementById('logout')
const sendForm = document.getElementById('send')
form.addEventListener('submit', (e) => {
e.preventDefault()
......@@ -10,3 +13,35 @@ form.addEventListener('submit', (e) => {
window.location = '/sign-in'
})
})
sendForm.addEventListener('submit', (e) => {
e.preventDefault()
const message = document.getElementById('message').value
const sessionKeyPromise = crypt.getSessionKey()
let encryptedMessage = ''
let secretSessionKey = ''
sessionKeyPromise.then((key) => {
secretSessionKey = key
const encryptedMessage = crypt.encrypt(secretSessionKey, message)
const publicKeyOther = axios.get('http://localhost:8181/encryptpublickey')
return Promise.all([encryptedMessage, publicKeyOther])
}).then((values) => {
encryptedMessage = values[0]
return crypt.pemPublicToCrypto(values[1].data.publicKey)
}).then((publicKeyOther) => {
crypt.encryptKey(publicKeyOther, secretSessionKey).then((encryptedSessionKey) => {
console.log('sessionkey', encryptedSessionKey)
console.log('encryptedMessage', encryptedMessage)
const data = {
sessionKey: encryptedSessionKey,
message: encryptedMessage
}
axios.post('http://localhost:8181/send', data, {headers: {'Content-Type': 'application/json'}})
})
}).catch((err) => {
console.log(err)
})
})
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment