-
Notifications
You must be signed in to change notification settings - Fork 37
/
Copy pathweb-browser-based-file-encryption-decryption.html
500 lines (417 loc) · 16.3 KB
/
web-browser-based-file-encryption-decryption.html
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Web Browser Based File Encryption / Decryption</title>
</head>
<style>
body {
font-family: 'Helvetica', 'Arial', 'sans-serif';
color: black;
font-size: 11pt;
}
a, a:link, a:visited, a:active {
color: blue;
text-decoration: underline;
}
a:hover {
cursor:pointer;
color: red;
}
.black10pointcourier {
font-family: 'courier';
color: black;
font-size: 10pt;
}
.container {
width: 80%;
margin: 0 auto;
}
.dropzone {
border: 10px dashed gray;
width: 20%;
padding: 2% 2% 5% 2%;
text-align: center;
margin: 5px 0 5px 0;
}
.divTablefullwidth{
display: table;
width: 100%;
}
.divTable{
display: table;
}
.divTableRow {
display: table-row;
}
.divTableCell {
display: table-cell;
padding: 3px 3px;
}
.divTableBody {
display: table-row-group;
}
.greenspan {
color: green;
}
.redspan {
color: red;
}
</style>
<body>
<div class=container>
<div class="divTablefullwidth">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell" style="float: left;">
<h1>Web Browser Based File Encryption / Decryption</h1>
<h4>Use your web browser to encrypt and decrypt files.</h4>
</div>
<div class="divTableCell" style="float: right;">
<h1>
<button id="btnRefresh" onClick="javascript:location.reload();">Refresh Page</button>
<button id="btnDivEncrypt" onClick="javascript:switchdiv('encrypt');">Encrypt a File</button>
<button id="btnDivDecrypt" onClick="javascript:switchdiv('decrypt');">Decrypt a File</button>
</h1>
</div>
</div>
</div>
</div>
</div>
<div class=container>
<hr>
</div>
<div class="container" id=divEncryptfile>
<h2>Encrypt a File</h2>
<p>To encrypt a file, enter a password and drop the file to be encrypted into the dropzone below. The file will then be encrypted using the password, then you'll be given an opportunity to save the encrypted file to your system.</p>
<div class="divTable">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell">Password</div>
<div class="divTableCell"><input id=txtEncpassphrase type=password size=30 onkeyup=javascript:encvalidate(); value=''></div>
<div class="divTableCell">(minumum length eight characters, make sure it strong!)</div>
</div>
<div class="divTableRow">
<div class="divTableCell">Password (retype)</div>
<div class="divTableCell"><input id=txtEncpassphraseretype type=password size=30 onkeyup=javascript:encvalidate(); value=''></div>
<div class="divTableCell"><span class=greenspan id=spnCheckretype></span></div>
</div>
</div>
</div>
<p> </p>
<div>
<div class=dropzone id="encdropzone" ondrop="drop_handler(event);" ondragover="dragover_handler(event);" ondragend="dragend_handler(event);">
<p>Drag and drop the file to be encrypted into this dropzone, or click <a onclick=javascript:encfileElem.click();>here</a> to select file.</p>
<p><span id=spnencfilename></span></p>
</div>
<input type="file" id="encfileElem" style="display:none" onchange="selectfile(this.files)">
</div>
<p> </p>
<div class="divTable">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell"><button id=btnEncrypt onclick=javascript:encryptfile(); disabled>Encrypt File</button></div>
<div class="divTableCell"><span id=spnEncstatus></span></div>
</div>
</div>
</div>
<p> </p>
<div>
<a id=aEncsavefile hidden><button>Save Encrypted File</button></a>
</div>
<p> </p>
</div>
<div class="container" id=divDecryptfile>
<h2>Decrypt a File</h2>
<p>Decrypt a file using the password that was previously used to encrypt the file. After the file is decrypted, you'll be given an opportunity to save the decrypted file to your system.</p>
<div class="divTable">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell">Password</div>
<div class="divTableCell"><input id=txtDecpassphrase type=password size=30 onkeyup=javascript:decvalidate(); value=''></div>
</div>
</div>
</div>
<p> </p>
<div>
<div class=dropzone id="decdropzone" ondrop="drop_handler(event);" ondragover="dragover_handler(event);" ondragend="dragend_handler(event);">
<p>Drag and drop file to be decrypted into this dropzone, or click <a role=button onclick=javascript:decfileElem.click();>here</a> to select file.</p>
<p><span id=spndecfilename></span></p>
</div>
<input type="file" id="decfileElem" style="display:none" onchange="selectfile(this.files)">
</div>
<p> </p>
<div class="divTable">
<div class="divTableBody">
<div class="divTableRow">
<div class="divTableCell"><button id=btnDecrypt onclick=javascript:decryptfile(); disabled>Decrypt File</button></div>
<div class="divTableCell"><span id=spnDecstatus></span></div>
</div>
</div>
</div>
<p> </p>
<div>
<a id=aDecsavefile hidden><button>Save Decrypted File</button></a>
</div>
<p> </p>
</div>
<div class="container">
<hr>
<h3>Usage</h3>
<p>
Use this web page to encrypt a file using a password, then use the same password later to decrypt the file. IMPORTANT: The same password that was used to encrypt the file must be used to decrypt the file later. If you loose or forget the password, it cannot be recovered!
</p>
<h3>Operation and privacy</h3>
<p>
This page uses javascript running within your web browser to encrypt and decrypt files client-side, in-browser.
This page makes no network connections during this process, to ensure that your files and keys never leave the web browser during the process.
This can be independently verified by reviewing the source code for this page, or by monitoring your web browser's <a href=https://developer.mozilla.org/en-US/docs/Tools/Network_Monitor>networking activity</a> during operation of this page.
This page can also be downloaded and run locally on your system offline.
</p>
<h3>Cryptography</h3>
<p>
All client-side cryptography is implemented using the <a href='https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API'>Web Crypto API</a>.
Files are encrypted using AES-CBC 256-bit symmetric encryption. The encryption key is derived from the password and a random salt using PBKDF2 derivation with 10000 iterations of SHA256 hashing.
</p>
<h3>Compatibility with openssl</h3>
<p>
The encryption used by this page is compatible with <a href='https://www.openssl.org/docs/man1.1.1/man1/openssl-enc.html'>openssl</a>.<BR>
<BR>
Files encrypted using this page can be decrypted using openssl using the following command:<BR>
<span class='black10pointcourier'>openssl aes-256-cbc -d -salt -pbkdf2 -iter 10000 -in <i>encryptedfilename</i> -out <i>plaintextfilename</i></span><BR>
<BR>
Files encrypted using the following openssl command can be decrypted using this page:<BR>
<span class='black10pointcourier'>openssl aes-256-cbc -e -salt -pbkdf2 -iter 10000 -in <i>plaintextfilename</i> -out <i>encryptedfilename</i></span><BR>
</p>
<h3>Running this page offline</h3>
<p>
This web page is self-contained. The page does not require any supporting files; all javascript and css for this page is contained in the source code of this page.
To run this page locally on your system offline, simply save this page to your system as a .html file, then open the file from your system in your web browser (optionally with networking disabled).
</p>
<h3>Verifying the integrity of this page</h3>
<p>
The expected SHA256 checksum hash of the .html file containing this page is posted at <a href=https://github.com/meixler/web-browser-based-file-encryption-decryption>https://github.com/meixler/web-browser-based-file-encryption-decryption</a>.
If loading this page from a web server, you can verify that the checksum hash of the .html file downloaded from the web server matches the expected checksum hash using the <a href=https://www.pageintegrity.net/>Page Integrity browser extension</a>.
If running this page offline, it is recommended that you verify that the checksum hash of the .html file matches the expected checksum hash before opening the file in your web browser.
</p>
<h3>License</h3>
<p>
This project is licensed under the <a href='https://www.gnu.org/licenses/gpl-3.0.en.html'>GPL-3.0</a> open source license.
</p>
<h3>GitHub</h3>
<p>
This project can be found on GitHub at <a href=https://github.com/meixler/web-browser-based-file-encryption-decryption>https://github.com/meixler/web-browser-based-file-encryption-decryption</a>.
</p>
<h3>Contact</h3>
<p>
Please <a href='https://www.meixler-tech.com/contact.php'>contact MTI</a> for any questions or comments concerning this project.
</p>
</div>
<BR>
</body>
</html>
<script type="text/javascript">
var mode=null;
var objFile=null;
switchdiv('encrypt');
function switchdiv(t) {
if(t=='encrypt') {
divEncryptfile.style.display='block';
divDecryptfile.style.display='none';
btnDivEncrypt.disabled=true;
btnDivDecrypt.disabled=false;
mode='encrypt';
} else if(t=='decrypt') {
divEncryptfile.style.display='none';
divDecryptfile.style.display='block';
btnDivEncrypt.disabled=false;
btnDivDecrypt.disabled=true;
mode='decrypt';
}
}
function encvalidate() {
if(txtEncpassphrase.value.length>=8 && txtEncpassphrase.value==txtEncpassphraseretype.value) {
spnCheckretype.classList.add("greenspan");
spnCheckretype.classList.remove("redspan");
spnCheckretype.innerHTML='✔';
} else {
spnCheckretype.classList.remove("greenspan");
spnCheckretype.classList.add("redspan");
spnCheckretype.innerHTML='✖';
}
if( txtEncpassphrase.value.length>=8 && txtEncpassphrase.value==txtEncpassphraseretype.value && objFile ) { btnEncrypt.disabled=false; } else { btnEncrypt.disabled=true; }
}
function decvalidate() {
if( txtDecpassphrase.value.length>0 && objFile ) { btnDecrypt.disabled=false; } else { btnDecrypt.disabled=true; }
}
//drag and drop functions:
//https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop
function drop_handler(ev) {
console.log("Drop");
ev.preventDefault();
// If dropped items aren't files, reject them
var dt = ev.dataTransfer;
if (dt.items) {
// Use DataTransferItemList interface to access the file(s)
for (var i=0; i < dt.items.length; i++) {
if (dt.items[i].kind == "file") {
var f = dt.items[i].getAsFile();
console.log("... file[" + i + "].name = " + f.name);
objFile=f;
}
}
} else {
// Use DataTransfer interface to access the file(s)
for (var i=0; i < dt.files.length; i++) {
console.log("... file[" + i + "].name = " + dt.files[i].name);
}
objFile=file[0];
}
displayfile()
if(mode=='encrypt') { encvalidate(); } else if(mode=='decrypt') { decvalidate(); }
}
function dragover_handler(ev) {
console.log("dragOver");
// Prevent default select and drag behavior
ev.preventDefault();
}
function dragend_handler(ev) {
console.log("dragEnd");
// Remove all of the drag data
var dt = ev.dataTransfer;
if (dt.items) {
// Use DataTransferItemList interface to remove the drag data
for (var i = 0; i < dt.items.length; i++) {
dt.items.remove(i);
}
} else {
// Use DataTransfer interface to remove the drag data
ev.dataTransfer.clearData();
}
}
function selectfile(Files) {
objFile=Files[0];
displayfile()
if(mode=='encrypt') { encvalidate(); } else if(mode=='decrypt') { decvalidate(); }
}
function displayfile() {
var s;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
var bytes=objFile.size;
var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
if(i==0) { s=bytes + ' ' + sizes[i]; } else { s=(bytes / Math.pow(1024, i)).toFixed(2) + ' ' + sizes[i]; }
if(mode=='encrypt') {
spnencfilename.textContent=objFile.name + ' (' + s + ')';
} else if(mode=='decrypt') {
spndecfilename.textContent=objFile.name + ' (' + s + ')';
}
}
function readfile(file){
return new Promise((resolve, reject) => {
var fr = new FileReader();
fr.onload = () => {
resolve(fr.result )
};
fr.readAsArrayBuffer(file);
});
}
async function encryptfile() {
btnEncrypt.disabled=true;
var plaintextbytes=await readfile(objFile)
.catch(function(err){
console.error(err);
});
var plaintextbytes=new Uint8Array(plaintextbytes);
var pbkdf2iterations=10000;
var passphrasebytes=new TextEncoder("utf-8").encode(txtEncpassphrase.value);
var pbkdf2salt=window.crypto.getRandomValues(new Uint8Array(8));
var passphrasekey=await window.crypto.subtle.importKey('raw', passphrasebytes, {name: 'PBKDF2'}, false, ['deriveBits'])
.catch(function(err){
console.error(err);
});
console.log('passphrasekey imported');
var pbkdf2bytes=await window.crypto.subtle.deriveBits({"name": 'PBKDF2', "salt": pbkdf2salt, "iterations": pbkdf2iterations, "hash": 'SHA-256'}, passphrasekey, 384)
.catch(function(err){
console.error(err);
});
console.log('pbkdf2bytes derived');
pbkdf2bytes=new Uint8Array(pbkdf2bytes);
keybytes=pbkdf2bytes.slice(0,32);
ivbytes=pbkdf2bytes.slice(32);
var key=await window.crypto.subtle.importKey('raw', keybytes, {name: 'AES-CBC', length: 256}, false, ['encrypt'])
.catch(function(err){
console.error(err);
});
console.log('key imported');
var cipherbytes=await window.crypto.subtle.encrypt({name: "AES-CBC", iv: ivbytes}, key, plaintextbytes)
.catch(function(err){
console.error(err);
});
if(!cipherbytes) {
spnEncstatus.classList.add("redspan");
spnEncstatus.innerHTML='<p>Error encrypting file. See console log.</p>';
return;
}
console.log('plaintext encrypted');
cipherbytes=new Uint8Array(cipherbytes);
var resultbytes=new Uint8Array(cipherbytes.length+16)
resultbytes.set(new TextEncoder("utf-8").encode('Salted__'));
resultbytes.set(pbkdf2salt, 8);
resultbytes.set(cipherbytes, 16);
var blob=new Blob([resultbytes], {type: 'application/download'});
var blobUrl=URL.createObjectURL(blob);
aEncsavefile.href=blobUrl;
aEncsavefile.download=objFile.name + '.enc';
spnEncstatus.classList.add("greenspan");
spnEncstatus.innerHTML='<p>File encrypted.</p>';
aEncsavefile.hidden=false;
}
async function decryptfile() {
btnDecrypt.disabled=true;
var cipherbytes=await readfile(objFile)
.catch(function(err){
console.error(err);
});
var cipherbytes=new Uint8Array(cipherbytes);
var pbkdf2iterations=10000;
var passphrasebytes=new TextEncoder("utf-8").encode(txtDecpassphrase.value);
var pbkdf2salt=cipherbytes.slice(8,16);
var passphrasekey=await window.crypto.subtle.importKey('raw', passphrasebytes, {name: 'PBKDF2'}, false, ['deriveBits'])
.catch(function(err){
console.error(err);
});
console.log('passphrasekey imported');
var pbkdf2bytes=await window.crypto.subtle.deriveBits({"name": 'PBKDF2', "salt": pbkdf2salt, "iterations": pbkdf2iterations, "hash": 'SHA-256'}, passphrasekey, 384)
.catch(function(err){
console.error(err);
});
console.log('pbkdf2bytes derived');
pbkdf2bytes=new Uint8Array(pbkdf2bytes);
keybytes=pbkdf2bytes.slice(0,32);
ivbytes=pbkdf2bytes.slice(32);
cipherbytes=cipherbytes.slice(16);
var key=await window.crypto.subtle.importKey('raw', keybytes, {name: 'AES-CBC', length: 256}, false, ['decrypt'])
.catch(function(err){
console.error(err);
});
console.log('key imported');
var plaintextbytes=await window.crypto.subtle.decrypt({name: "AES-CBC", iv: ivbytes}, key, cipherbytes)
.catch(function(err){
console.error(err);
});
if(!plaintextbytes) {
spnDecstatus.classList.add("redspan");
spnDecstatus.innerHTML='<p>Error decrypting file. Password may be incorrect.</p>';
return;
}
console.log('ciphertext decrypted');
plaintextbytes=new Uint8Array(plaintextbytes);
var blob=new Blob([plaintextbytes], {type: 'application/download'});
var blobUrl=URL.createObjectURL(blob);
aDecsavefile.href=blobUrl;
aDecsavefile.download=objFile.name + '.dec';
spnDecstatus.classList.add("greenspan");
spnDecstatus.innerHTML='<p>File decrypted.</p>';
aDecsavefile.hidden=false;
}
</script>