changed from using input fields for keys to getting from url (#17)

* changed from using input fields for keys to getting from url

* cleaned
This commit is contained in:
Abhinav Adduri 2017-05-30 14:45:15 -07:00 committed by Danny Coates
parent a45bcf3d35
commit 7b841e9498
3 changed files with 53 additions and 73 deletions

9
app.js
View File

@ -29,7 +29,6 @@ app.get('/assets/download/:id', function(req, res) {
res.send('error'); res.send('error');
} else { } else {
res.setHeader('Content-Disposition', 'attachment; filename=' + reply); res.setHeader('Content-Disposition', 'attachment; filename=' + reply);
// res.setHeader('Content-Transfer-Encoding', 'binary');
res.setHeader('Content-Type', 'application/octet-stream'); res.setHeader('Content-Type', 'application/octet-stream');
res.download(__dirname + '/static/' + reply); res.download(__dirname + '/static/' + reply);
@ -38,7 +37,7 @@ app.get('/assets/download/:id', function(req, res) {
}); });
app.route('/upload') app.route('/upload/:id')
.post(function (req, res, next) { .post(function (req, res, next) {
var fstream; var fstream;
@ -50,11 +49,11 @@ app.route('/upload')
fstream = fs.createWriteStream(__dirname + '/static/' + filename); fstream = fs.createWriteStream(__dirname + '/static/' + filename);
file.pipe(fstream); file.pipe(fstream);
fstream.on('close', function () { fstream.on('close', function () {
let id = Math.floor(Math.random()*10000).toString(); let id = req.params.id;
client.hset(id, "filename", filename, redis.print); client.hset(id, "filename", filename, redis.print);
client.hset(id, "expiration", 0, redis.print); client.hset(id, "expiration", 0, redis.print);
console.log("Upload Finished of " + filename); console.log("Upload Finished of " + filename);
res.send(id); //where to go next res.send(id);
}); });
}); });
}); });
@ -62,6 +61,6 @@ app.route('/upload')
app.listen(3000, function () { app.listen(3000, function () {
console.log('Example app listening on port 3000!') console.log('Portal app listening on port 3000!')
}) })

View File

@ -3,16 +3,10 @@
<head> <head>
<title>Page Title</title> <title>Page Title</title>
<script type="text/javascript" src="/file.js"></script> <script type="text/javascript" src="/file.js"></script>
</head> </head>
<body> <body>
<input id="keyhash" placeholder="Paste the key your friend sent you."/><br />
<input id="salt" placeholder="Paste the salt your friend sent you."/><br />
<button onclick="download()">DOWNLOAD</button> <button onclick="download()">DOWNLOAD</button>
</body> </body>
</html> </html>

View File

@ -1,11 +1,8 @@
function download() { function download() {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.open('get', '/assets' + location.pathname, true); xhr.open('get', '/assets' + location.pathname.slice(0, -1), true);
xhr.responseType = 'blob'; xhr.responseType = 'blob';
// $.each(SERVER.authorization(), function(k, v) {
// xhr.setRequestHeader(k, v);
// });
// xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.onload = function(e) { xhr.onload = function(e) {
if (this.status == 200) { if (this.status == 200) {
@ -15,36 +12,33 @@ function download() {
var fileReader = new FileReader(); var fileReader = new FileReader();
fileReader.onload = function() { fileReader.onload = function() {
arrayBuffer = this.result; arrayBuffer = this.result;
// console.log(arrayBuffer);
var array = new Uint8Array(arrayBuffer); var array = new Uint8Array(arrayBuffer);
salt = new Uint8Array(JSON.parse(document.getElementById('salt').value)); salt = strToIv(location.pathname.slice(10, -1));
window.crypto.subtle.importKey( window.crypto.subtle.importKey(
"jwk", //can be "jwk" or "raw" "jwk",
{ //this is an example jwk key, "raw" would be an ArrayBuffer {
kty: "oct", kty: "oct",
k: document.getElementById('keyhash').value, k: location.hash.slice(1),
alg: "A128CBC", alg: "A128CBC",
ext: true, ext: true,
}, },
{ //this is the algorithm options {
name: "AES-CBC", name: "AES-CBC",
}, },
true, //whether the key is extractable (i.e. can be used in exportKey) true,
["encrypt", "decrypt"] //can be "encrypt", "decrypt", "wrapKey", or "unwrapKey" ["encrypt", "decrypt"]
) )
.then(function(key){ .then(function(key){
//returns the symmetric key
window.crypto.subtle.decrypt( window.crypto.subtle.decrypt(
{ {
name: "AES-CBC", name: "AES-CBC",
iv: salt, //The initialization vector you used to encrypt iv: salt,
}, },
key, //from generateKey or importKey above key,
array //ArrayBuffer of the data array
) )
.then(function(decrypted){ .then(function(decrypted){
//returns an ArrayBuffer containing the decrypted data
// let original = new Uint8Array(decrypted);
var dataView = new DataView(decrypted); var dataView = new DataView(decrypted);
var blob = new Blob([dataView]); var blob = new Blob([dataView]);
var downloadUrl = URL.createObjectURL(blob); var downloadUrl = URL.createObjectURL(blob);
@ -57,20 +51,12 @@ function download() {
.catch(function(err){ .catch(function(err){
console.error(err); console.error(err);
}); });
// console.log(key);
}) })
.catch(function(err){ .catch(function(err){
console.error(err); console.error(err);
}); });
}; };
fileReader.readAsArrayBuffer(blob); fileReader.readAsArrayBuffer(blob);
// console.log(blob);
// var downloadUrl = URL.createObjectURL(blob);
// var a = document.createElement("a");
// a.href = downloadUrl;
// // a.download = "feheroes.png";
// document.body.appendChild(a);
// a.click();
} else { } else {
alert('Unable to download excel.') alert('Unable to download excel.')
} }
@ -82,50 +68,44 @@ function onChange(event) {
var file = event.target.files[0]; var file = event.target.files[0];
var reader = new FileReader(); var reader = new FileReader();
reader.onload = function(event) { reader.onload = function(event) {
// The file's text will be printed here
let self = this; let self = this;
window.crypto.subtle.generateKey({ window.crypto.subtle.generateKey({
name: "AES-CBC", name: "AES-CBC",
length: 128 length: 128
}, },
true, //whether the key is extractable (i.e. can be used in exportKey) true,
["encrypt", "decrypt"]) ["encrypt", "decrypt"])
.then(function(key){ .then(function(key){
//returns a key object
var arrayBuffer = self.result; var arrayBuffer = self.result;
var array = new Uint8Array(arrayBuffer); var array = new Uint8Array(arrayBuffer);
// binaryString = String.fromCharCode.apply(null, array);
// console.log(binaryString);
// console.log(file);
var random_iv = window.crypto.getRandomValues(new Uint8Array(16)); var random_iv = window.crypto.getRandomValues(new Uint8Array(16));
window.crypto.subtle.encrypt({ window.crypto.subtle.encrypt({
name: "AES-CBC", name: "AES-CBC",
//Don't re-use initialization vectors! iv: random_iv },
//Always generate a new iv every time your encrypt! key,
iv: random_iv}, array)
key, //from generateKey or importKey above
array //ArrayBuffer of data you want to encrypt
)
.then(function(encrypted){ .then(function(encrypted){
console.log('Send this salt to a friend: [' + random_iv.toString() + ']'); console.log('Send this salt to a friend: [' + random_iv.toString() + ']');
// console.log(arrayBuffer);
//returns an ArrayBuffer containing the encrypted data
var dataView = new DataView(encrypted); var dataView = new DataView(encrypted);
var blob = new Blob([dataView], { type: file.type }); var blob = new Blob([dataView], { type: file.type });
window.data = encrypted;
var fd = new FormData(); var fd = new FormData();
fd.append('fname', file.name); fd.append('fname', file.name);
fd.append('data', blob, file.name); fd.append('data', blob, file.name);
// console.log(blob);
var xhr = new XMLHttpRequest();
xhr.open('post', '/upload', true); var xhr = new XMLHttpRequest();
var hex = ivToStr(random_iv);
xhr.open('post', '/upload/' + hex, true);
xhr.onreadystatechange = function() { xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) { if (xhr.readyState == XMLHttpRequest.DONE) {
console.log('Go to this URL: http://localhost:3000/download/'+xhr.responseText); window.crypto.subtle.exportKey("jwk", key).then(function(keydata){
console.log('Go to this URL: http://localhost:3000/download/' + hex + '/#' + keydata.k);
alert('Go to this URL: http://localhost:3000/download/' + hex + '/#' + keydata.k);
})
} }
}; };
@ -135,26 +115,33 @@ function onChange(event) {
console.error(err); console.error(err);
}); });
window.crypto.subtle.exportKey(
"jwk", //can be "jwk" or "raw"
key)
.then(function(keydata){
//returns the exported key data
console.log('Send this key to a friend: ' + keydata.k);
}) })
.catch(function(err){ .catch(function(err){
console.error(err); console.error(err);
}); });
})
.catch(function(err){
console.error(err);
});
}; };
reader.readAsArrayBuffer(file); reader.readAsArrayBuffer(file);
} }
function ivToStr(iv) {
let hexStr = '';
for (var i in iv) {
if (iv[i] < 16) {
hexStr += '0' + iv[i].toString(16);
} else {
hexStr += iv[i].toString(16);
}
}
window.hexStr = hexStr;
return hexStr;
}
function strToIv(str) {
var iv = new Uint8Array(16);
for (var i = 0; i < str.length; i += 2) {
iv[i/2] = parseInt((str.charAt(i) + str.charAt(i + 1)), 16);
}
return iv;
}