-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
525 lines (433 loc) · 14 KB
/
index.html
File metadata and controls
525 lines (433 loc) · 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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
<!DOCTYPE html>
<html lang="en">
<head>
<script type="encrypted" data-el="store">null</script>
<meta charset="utf-8" />
<title>Encrypt to HTML</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"
integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous" />
<style>
textarea {
font-family: monospace;
white-space: pre-wrap;
width: 90%;
height: 10em;
}
[hidden] {
display: none !important;
}
body {
margin: 2em 0;
}
header {
margin: 0 2em 2em;
}
section {
margin: 0 2em;
}
footer {
margin-top: 2em;
padding: 1em 2em 0 2em;
border-top: 1px solid #ccc;
}
textarea {
font-family: monospace;
}
input[data-el="file"] {
display: inline-block;
}
#file_base {
width: 10em;
display: inline-block;
vertical-align: middle;
}
[for="pwd1"] small {
font-style: italic;
}
[type="submit"] img {
height: 1em;
margin-left: 5px;
}
</style>
</head>
<body>
<header>
<h1 class="text-muted">Encrypt to HTML</h1>
<p>
Encrypt a message/file to a standalone HTML file that can be decrypted offline.
</p>
<p>
100% client-side. <a href="./" download="encrypt-to-html.html">Download</a> and use it
anywhere. (<a href="https://github.com/mrclay/encrypt-to-html/blob/master/index.html"
target="_blank" rel="noopener">Unminified source</a>)
</p>
</header>
<section data-el="alert" hidden>
<div class="alert alert-success" role="alert">
<p data-el="alertMsg"></p>
</div>
</section>
<section data-el="encrypt" hidden>
<div class="form-group">
<label for="msg">Sensitive Content</label> ...or <input type="file" data-el="file" />
<textarea class="form-control" rows="5" id="msg" autofocus data-el="in" required></textarea>
</div>
<div class="form-group">
<label for="pwd1">Password (repeat) <small>Use a strong one!</small></label>
<input type="password" data-el="pwd1" class="form-control" id="pwd1" required autocomplete="off" />
<input type="password" data-el="pwd2" class="form-control" id="pwd2" required autocomplete="off" />
</div>
<div class="form-group">
<label for="file_base">Target file </label>
<input class="form-control" type="text" data-el="name" id="file_base" value="my-secret" required />
.html
</div>
<button data-el="encryptBtn" class="btn btn-primary"></button>
</section>
<section data-el="decrypt" hidden>
<div data-el="pwdWrapper">
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" data-el="pwd" class="form-control" id="pwd" required autocomplete="off" />
</div>
<p>
<button data-el="decryptBtn" class="btn btn-primary">Decrypt</button>
</p>
</div>
<div class="form-group" data-el="outWrapper">
<label for="msg_out">Stored Content</label>
<textarea class="form-control" rows="10" id="msg_out" autofocus data-el="out" readonly></textarea>
</div>
<div>
<p><button data-el="reset" class="btn btn-primary">Encrypt something new</button></p>
</div>
</section>
<footer>
<p>
By <a href="http://www.mrclay.org/">Steve Clay</a>.
<a href="https://github.com/mrclay/encrypt-to-html">Source</a>.
Uses WebCrypto (256-bit AES-GCM, PBKDF2 key generation with at least 500K rounds). Version 2.0.
</p>
<p>
Dig it? Send me something on my
<a href="https://www.amazon.com/hz/wishlist/ls/2QG3N5JPO53BD?ref_=wl_share">wish list</a>.
</p>
</footer>
<script>
(async () => {
// Encryption lib
const getKeyMaterial = (password) =>
crypto.subtle.importKey(
"raw",
new TextEncoder().encode(password),
"PBKDF2",
false,
["deriveBits", "deriveKey"]
);
async function decrypt(
password,
iterations,
salt,
iv,
encryptedBuffer
) {
const keyMaterial = await getKeyMaterial(password);
const key = await crypto.subtle.deriveKey(
{ name: "PBKDF2", salt, iterations, hash: "SHA-256" },
keyMaterial,
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
return crypto.subtle
.decrypt({ name: "AES-GCM", iv }, key, encryptedBuffer);
}
async function encrypt(password, plaintext) {
const iv = crypto.getRandomValues(new Uint8Array(16));
const salt = crypto.getRandomValues(new Uint8Array(16));
let keyMaterial = await getKeyMaterial(password);
let iterations = 5000000;
let key;
for (let i = 0; i < 20; i++) {
const startTime = performance.now();
key = await crypto.subtle.deriveKey(
{ name: "PBKDF2", salt, iterations, hash: "SHA-256" },
keyMaterial,
{ name: "AES-GCM", length: 256 },
true,
["encrypt", "decrypt"]
);
if (performance.now() - startTime > 500) {
break;
}
iterations = Math.round(iterations * 1.5);
}
const encryptedBuffer = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
key,
plaintext
);
return {
encryptedBuffer,
iterations,
salt,
iv,
};
}
const base64FromBuffer = (buffer) =>
btoa(
new Uint8Array(buffer).reduce(
(data, byte) => data + String.fromCharCode(byte),
""
)
);
const bufferFromBase64 = (base64) => {
const binaryString = atob(base64);
const len = binaryString.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
};
// Allow pushing files to browser
function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.style.display = "none";
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
URL.revokeObjectURL(url);
}
// Pseudo-reactive state
const SUCCESS = "success";
const MODE_ENCRYPT = 1;
const MODE_DECRYPT = 2;
let state = {
alertMsg: "",
alertType: SUCCESS,
done: false,
filename: "",
input: "",
inputHeight: 0,
mode: MODE_ENCRYPT,
output: "",
password: "",
storedData: null,
working: false,
};
let lastState = { ...state };
function setState(obj) {
lastState = { ...state };
const mixed = typeof obj === "function" ? obj(state) : obj;
state = { ...state, ...mixed };
preRenderSideEffects();
updateDom();
}
function preRenderSideEffects() {
const { mode, input, output, password, filename } = state;
if (lastState.filename !== filename) {
dom.name.value = filename;
}
if (mode !== lastState.mode) {
if (mode === MODE_ENCRYPT) {
state.input = output;
dom.in.value = output;
state.filename = "";
dom.pwd1.value = password;
dom.pwd2.value = password;
}
}
}
// DOM manipulation
const dom = {};
function updateDom() {
// These elements always visible...
const visible = ["alertMsg", "pwd1", "pwd2", "encryptBtn", "file", "name", "out", "pwd", "decryptBtn"];
const WORKING = "⏳ Working...";
if (state.mode === MODE_ENCRYPT) {
visible.push("encrypt");
if (!state.filename) {
visible.push("in");
}
dom.encryptBtn.textContent = state.working ? WORKING : "Download file";
dom.encryptBtn.style.opacity = state.working ? ".6" : "";
} else {
// Decrypt
visible.push("decrypt");
if (state.done) {
visible.push("outWrapper", "reset");
} else {
visible.push("pwdWrapper");
}
dom.decryptBtn.textContent = state.working ? WORKING : "Decrypt";
dom.decryptBtn.style.opacity = state.working ? ".6" : "";
}
if (state.alertMsg) {
dom.alertMsg.textContent = state.alertMsg;
dom.alert.querySelector("div").className = `alert alert-${state.alertType}`;
visible.push("alert");
}
// Hide data-el elements not marked as visible
document.querySelectorAll("[data-el]").forEach((el) => {
el.hidden = !visible.includes(el.dataset.el);
});
dom.out.value = state.output;
}
// Actions
const actions = {
adjustInputHeight() {
if (dom.in.scrollHeight > dom.in.offsetHeight + 10) {
dom.in.style.height = (dom.in.scrollHeight + 10) + 'px';
}
},
setFilename: () => setState({ filename: dom.file.files[0].name }),
onFocusName() {
if (dom.name.value === "my-secret") {
dom.name.select();
}
},
async doEncrypt() {
if (state.working) {
return;
}
if (dom.pwd1.value !== dom.pwd2.value) {
setState({
alertMsg: "Passwords do not match",
alertType: "warning",
});
return;
}
if (dom.pwd1.value.length < 6) {
setState({
alertMsg: "Password less than 6 characters",
alertType: "warning",
});
return;
}
const password = dom.pwd1.value;
// Encryption
const files = dom.file.files;
setState({
input: dom.in.value,
password,
working: true,
});
let plaintext = (new TextEncoder()).encode(dom.in.value);
if (files[0]) {
plaintext = await new Promise(res => {
reader = new FileReader();
reader.onload = (e) => res(e.target.result);
reader.readAsArrayBuffer(files[0]);
});
}
encrypt(password, plaintext).then((res) => {
const { iterations, salt, iv, encryptedBuffer } = res;
const encryptData = [
state.filename,
iterations,
base64FromBuffer(salt),
base64FromBuffer(iv),
base64FromBuffer(encryptedBuffer),
];
dom.store.textContent = JSON.stringify(encryptData);
document.querySelectorAll("[hidden]").forEach(el => el.removeAttribute("hidden"));
// Capture HTML
const blob = new Blob(
["<!DOCTYPE html>", document.querySelector('html').outerHTML],
{ type: "text/html" }
);
downloadBlob(blob, dom.name.value + ".html");
setState({
alertMsg: "Your message/file was encrypted to an HTML file.",
alertType: SUCCESS,
done: true,
working: false,
});
});
},
doDecrypt() {
if (state.working) {
return;
}
const [filename, iterations, strSalt, strIv, strEncrypted] = state.storedData;
const password = dom.pwd.value;
setState({
password,
working: true,
});
const salt = bufferFromBase64(strSalt);
const iv = bufferFromBase64(strIv);
const encryptedBuffer = bufferFromBase64(strEncrypted);
decrypt(dom.pwd.value, iterations, salt, iv, encryptedBuffer)
.then((decryptedBuffer) => {
let decrypted = "";
let alertMsg = "";
if (filename) {
const blob = new Blob([decryptedBuffer]);
downloadBlob(blob, filename);
alertMsg = "Decrypted file downloaded.";
} else {
decrypted = (new TextDecoder()).decode(decryptedBuffer);
alertMsg = "Message decrypted."
}
setState({
alertMsg,
alertType: SUCCESS,
done: true,
output: decrypted,
working: false,
});
})
.catch((e) => {
setState({
alertMsg: String(e),
alertType: "danger",
working: false,
});
});
},
reset() {
// Encrypt something new with same password
setState({
alertMsg: "",
done: false,
input: state.output,
mode: MODE_ENCRYPT,
});
}
};
// Setup, events
document.addEventListener("DOMContentLoaded", () => {
document.querySelectorAll("[data-el]").forEach((el) => {
dom[el.dataset.el] = el;
});
setInterval(actions.adjustInputHeight, 1000);
dom.file.addEventListener("change", actions.setFilename);
dom.name.addEventListener("focus", actions.onFocusName);
dom.encryptBtn.addEventListener("click", actions.doEncrypt);
dom.pwd2.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
actions.doEncrypt();
}
});
dom.decryptBtn.addEventListener("click", actions.doDecrypt);
dom.pwd.addEventListener("keydown", (e) => {
if (e.key === "Enter") {
actions.doDecrypt();
}
});
dom.reset.addEventListener("click", actions.reset);
const storedData = JSON.parse(dom.store.textContent);
// Go!
setState({
mode: storedData ? MODE_DECRYPT : MODE_ENCRYPT,
storedData,
});
});
})();
</script>
</body>
</html>