-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcloaker.js
More file actions
288 lines (267 loc) · 9.14 KB
/
cloaker.js
File metadata and controls
288 lines (267 loc) · 9.14 KB
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
import * as c from './constants.js';
let inFile;
// check for FileSystem API
let streaming = !!window.showSaveFilePicker;
// used when streaming
let outFile;
let outHandle;
let outStream;
// used when not streaming
let outBuffers;
// writes encrypted/decrypted data to stream or the buffer to be downloaded
let writeData;
// these set up output and kick off worker.js
let startEncryption;
let startDecryption;
let selectFileButton = document.getElementById('selectFileButton');
let selectFileElem = document.getElementById('selectFileElem');
let encryptButton = document.getElementById('encryptButton');
let encryptElem = document.getElementById('encryptElem');
let decryptButton = document.getElementById('decryptButton');
let decryptElem = document.getElementById('decryptElem');
let passwordTitle = document.getElementById('passwordTitle');
let passwordBox = document.getElementById('passwordBox');
let outputBox = document.getElementById('outputBox');
let progressBar = document.getElementById('progressBar');
let speedSpan = document.getElementById('speed');
let streamingSpan = document.getElementById('streamingSpan');
let nonStreamingSpan = document.getElementById('nonStreamingSpan');
let startTime;
let progress;
let speed;
let progressInterval;
window.onload = () => {
selectFileButton.onclick = () => selectFileElem.click();
selectFileElem.oninput = async () => {
inFile = selectFileElem.files[0];
let firstFour = await inFile.slice(0, 4).arrayBuffer();
firstFour = new Uint8Array(firstFour);
let hasSignature = compareArrays(firstFour, c.SIGNATURE)
|| compareArrays(firstFour, c.LEGACY_SIGNATURE);
let decrypting = extensionIsCloaker(inFile.name) || hasSignature;
if (decrypting) {
encryptButton.style = 'display: hidden';
decryptButton.style = 'display: unset';
} else {
encryptButton.style = 'display: unset';
decryptButton.style = 'display: hidden';
}
output(`File to ${decrypting ? "decrypt" : "encrypt"}: ${inFile.name}, size: ${getHumanReadableFileSize(inFile.size)}`);
}
encryptButton.onclick = async () => {
if (!inFile) {
output('Please select file.');
return;
}
// check password
const password = passwordBox.value;
if (password.length < 12) {
passwordBox.classList.add('passwordError');
setTimeout(() => {
passwordBox.classList.remove('passwordError');
}, 1000);
passwordTitle.classList.add('passwordErrorTitle');
setTimeout(() => {
passwordTitle.classList.remove('passwordErrorTitle');
}, 4000);
return;
}
// set up file output
let name = inFile.name + c.EXTENSION;
if (streaming) {
outHandle = await window.showSaveFilePicker({
suggestedName: name,
types: [{
description: 'Cloaker',
accept: {'application/cloaker': [c.EXTENSION]},
}],
});
outFile = await outHandle.getFile();
outStream = await outHandle.createWritable();
name = outFile.name; // use whatever name user picked
}
output(`Output filename: ${name}`);
startEncryption(inFile, password);
};
decryptButton.onclick = async () => {
if (!inFile) {
output('Please select file.');
return;
}
const password = passwordBox.value;
let name = getDecryptFilename(inFile.name);
if (streaming) {
outHandle = await window.showSaveFilePicker({
suggestedName: getDecryptFilename(inFile.name),
});
outFile = await outHandle.getFile();
outStream = await outHandle.createWritable();
name = outFile.name; // use whatever name user picked
}
output(`Output filename: ${name}`);
startDecryption(inFile, password);
};
if (streaming) {
streamingSpan.style = 'display: unset';
nonStreamingSpan.style = 'display: none';
} else {
streamingSpan.style = 'display: none';
nonStreamingSpan.style = 'display: unset';
}
};
let worker = new Worker('./worker.js');
worker.onmessage = (message) => {
// console.log('main received:', message);
let bytesPerSecond, download, link, name;
switch (message.data.response) {
case c.INITIALIZED_ENCRYPTION:
launchProgress();
writeData(message.data.header);
worker.postMessage({ command: c.ENCRYPT_CHUNK }); // kick off actual encryption
break;
case c.ENCRYPTED_CHUNK:
writeData(message.data.encryptedChunk);
bytesPerSecond = message.data.bytesWritten / ((Date.now() - startTime) / 1000);
speed = getHumanReadableFileSize(bytesPerSecond) + '/sec';
progress = message.data.progress;
worker.postMessage({ command: c.ENCRYPT_CHUNK }); // next chunk
break;
case c.FINAL_ENCRYPTION:
writeData(message.data.encryptedChunk);
if (streaming) {
name = outFile.name;
outStream.close();
} else {
name = inFile.name + c.EXTENSION;
download = new File(outBuffers, name);
link = document.getElementById('downloadLink');
link.download = name;
link.href = URL.createObjectURL(download);
link.innerText = `Download encrypted file "${name}"`
link.style = 'display: unset';
}
output(`Encryption of ${name} complete.`);
output();
progressBar.value = message.data.progress;
clearInterval(progressInterval);
break;
case c.INITIALIZED_DECRYPTION:
launchProgress();
worker.postMessage({ command: c.DECRYPT_CHUNK }); // kick off decryption
break;
case c.DECRYPTED_CHUNK:
writeData(message.data.decryptedChunk);
bytesPerSecond = message.data.bytesWritten / ((Date.now() - startTime) / 1000);
speed = getHumanReadableFileSize(bytesPerSecond) + '/sec';
progress = message.data.progress;
worker.postMessage({ command: c.DECRYPT_CHUNK });
break;
case c.FINAL_DECRYPTION:
writeData(message.data.decryptedChunk);
if (streaming) {
name = outFile.name;
outStream.close();
} else {
name = getDecryptFilename(inFile.name);
download = new File(outBuffers, name);
link = document.getElementById('downloadLink');
link.download = name;
link.href = URL.createObjectURL(download);
link.innerText = `Download decrypted file "${name}"`
link.style = 'display: unset';
}
output(`Decryption of ${name} complete.`);
output();
progressBar.value = message.data.progress;
clearInterval(progressInterval);
break;
case c.DECRYPTION_FAILED:
output('Incorrect password');
clearInterval(progressInterval);
break;
}
};
startEncryption = async (inFile, password) => {
startTime = Date.now();
let salt = new Uint8Array(c.crypto_pwhash_argon2id_SALTBYTES);
window.crypto.getRandomValues(salt);
if (streaming) {
outStream.write(c.SIGNATURE);
outStream.write(salt);
} else {
outBuffers = [new Uint8Array(c.SIGNATURE)];
outBuffers.push(salt);
}
worker.postMessage({ inFile, password, salt, command: c.START_ENCRYPTION });
}
startDecryption = async (inFile, password) => {
startTime = Date.now();
if (!streaming) {
outBuffers = [];
}
worker.postMessage({ inFile, password, command: c.START_DECRYPTION });
}
writeData = (data) => {
if (streaming) {
outStream.write(data);
} else {
outBuffers.push(data);
}
}
const output = (msg) => {
if (window.getComputedStyle(outputBox).display === 'none') {
outputBox.style = 'display: unset';
}
let message = document.createElement('span');
message.textContent = msg;
outputBox.appendChild(message);
outputBox.appendChild(document.createElement('br'));
}
const launchProgress = () => {
speedSpan.style = 'display: unset';
progressBar.style = 'display: unset';
progressInterval = setInterval( () => {
speedSpan.textContent = 'Speed: ' + speed;
progressBar.value = progress;
}, 250);
}
const compareArrays = (a1, a2) => {
if (!a1.length || a1.length != a2.length) {
return false;
}
for (let i = 0; i < a1.length; i++) {
if (a1[i] != a2[i]) {
return false;
}
}
return true;
}
const extensionIsCloaker = (filename) => {
return filename.length > c.EXTENSION.length
&& filename.slice(filename.length - c.EXTENSION.length, filename.length) === c.EXTENSION;
}
const getDecryptFilename = (filename) => {
// if filename is longer than .cloaker and ends with .cloaker, chop off extension. if not, leave as is and let the user or OS decide.
let suffixes = [c.EXTENSION, c.EXTENSION + '.txt']; // Chrome on Android adds .cloaker.txt for some reason
let decryptFilename = filename;
for (let i in suffixes) {
let len = suffixes[i].length;
if (filename.length > len && filename.slice(filename.length - len, filename.length) === suffixes[i]) {
decryptFilename = filename.slice(0, filename.length - len);
}
}
return decryptFilename;
}
const getHumanReadableFileSize = (size) => {
if (size < 1000) {
return size.toFixed(0) + ' bytes';
} else if (size < 1000000) {
return (size/1000).toFixed(2) + 'KB';
} else if (size < 1000000000) {
return (size/1000000).toFixed(2) + 'MB';
} else if (size < 1000000000000) {
return (size/1000000000).toFixed(2) + 'GB';
} else {
return (size/1000000000000).toFixed(2) + 'TB';
}
}