/* jsaccess - download and decrypt files in the browser * 2013, Laurent Ghigonis */ /* Reference code */ //console.log(JSON.stringify(xhr)); /* ===== PUBLIC - called by html ===== */ /* Called on "body" load */ function jsainit() { } /* Called on "Get files list" click */ function jsagetlist() { var pass = document.getElementById('password').value; var RMD160 = new Hashes.RMD160; var hash = RMD160.hex(pass); _status("Getting file list ..."); listreq = $.ajax({ url: 'files/' + hash + '/index.txt', beforeSend: function ( xhr ) { xhr.overrideMimeType("application/base64"); }, success: function ( data ) { _status("We have file list"); _showfiles(data, pass, hash); }, error: function (xhr, opts, err) { _status("Bad password"); throw(err); } }); } /* Called on "Download" click */ function jsadl() { var pass = document.getElementById('password').value; var file = $('input[name=file]:checked').val(); obj = _dl(file, pass); } /* ===== PRIVATE - called within this javascript file ===== */ function _showfiles(data, pass, hash) { try { var decrypted = GibberishAES.dec(data, pass); } catch(err) { _status(err.toString()); throw err; } document.getElementById('files').innerHTML = ""; lines = decrypted.split("\n").filter(function(n){return n}); $.each(lines, function( idx, obj ){ obj = obj.trim(); var btn = $(''+obj+'
'); btn.appendTo('#files'); }); } function _dl(file, pass) { var RMD160 = new Hashes.RMD160; var dirhash = RMD160.hex(pass); var path = 'files/' + dirhash + '/' + RMD160.hex(dirhash + file); _status("Downloading \""+file+"\" ..."); dlreq = $.ajax({ url: path, beforeSend: function ( xhr ) { xhr.overrideMimeType("application/base64"); }, success: function ( data ) { _status("Download complete, decrypting ..."); _decrypt(data, pass, file); }, error: function (xhr, opts, err) { _status("Dowload failed (status="+xhr.status+")"); throw(err); } }); } function _decrypt(obj, pass, name) { try { var decrypted = GibberishAES.dec(obj, pass); } catch(err) { _status(err.toString()); throw err; } out = $.base64.decode(decrypted.toString()); _status("Decrypted successfuly, saving ..."); _save(out, name); } function _save(obj, name) { var ab = new ArrayBuffer(obj.length); var ia = new Uint8Array(ab); for (var i = 0; i < obj.length; i++) { ia[i] = obj.charCodeAt(i); } var blob = new Blob([ia], {type:"application/octet-binary"}); saveAs(blob, name); _status("File \""+name+"\" saved."); _status("Have a good day."); } function _status(txt) { var div = document.getElementById('status'); div.innerHTML = div.innerHTML + '
' + txt; }