-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
721 lines (604 loc) · 23.7 KB
/
Copy pathapp.js
File metadata and controls
721 lines (604 loc) · 23.7 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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
/**
* SecureStream - app.js
* Senior cryptography-aware web engineer implementation.
*/
'use strict';
// --- Constants ---
const MAGIC = "FENC";
const VERSION = 2;
const KDF_PBKDF2 = 1;
const PBKDF2_ITERATIONS = 310000;
const SALT_LEN = 16;
const CHUNK_SIZE = 4 * 1024 * 1024; // 4 MiB
const IV_BASE_LEN = 12;
const MAC_NONE = 0;
const MAC_HMAC_SHA256 = 1;
// --- State ---
let selectedFile = null;
let currentOperation = null; // 'encrypt' | 'decrypt'
// --- UI Elements ---
const encryptTab = document.getElementById('encryptTab');
const decryptTab = document.getElementById('decryptTab');
const encryptPanel = document.getElementById('encryptPanel');
const decryptPanel = document.getElementById('decryptPanel');
const dropZone = document.getElementById('dropZone');
const fileInput = document.getElementById('fileInput');
const dropZoneDecrypt = document.getElementById('dropZoneDecrypt');
const fileInputDecrypt = document.getElementById('fileInputDecrypt');
const encryptBtn = document.getElementById('encryptBtn');
const decryptBtn = document.getElementById('decryptBtn');
const progressContainer = document.getElementById('progressContainer');
const progressBarFill = document.getElementById('progressBarFill');
const statusText = document.getElementById('statusText');
const percentText = document.getElementById('percentText');
const speedText = document.getElementById('speedText');
const etaText = document.getElementById('etaText');
const errorLog = document.getElementById('errorLog');
// --- Initialization ---
// Register Service Worker for streaming fallback
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js').catch(err => {
console.error('Service Worker registration failed:', err);
});
}
// --- Event Listeners ---
encryptTab.addEventListener('click', () => {
encryptTab.classList.add('active');
decryptTab.classList.remove('active');
encryptPanel.classList.remove('hidden');
decryptPanel.classList.add('hidden');
currentOperation = 'encrypt';
});
decryptTab.addEventListener('click', () => {
decryptTab.classList.add('active');
encryptTab.classList.remove('active');
decryptPanel.classList.remove('hidden');
encryptPanel.classList.add('hidden');
currentOperation = 'decrypt';
});
// Drag & Drop logic
[dropZone, dropZoneDecrypt].forEach(zone => {
zone.addEventListener('dragover', (e) => {
e.preventDefault();
zone.classList.add('drag-over');
});
zone.addEventListener('dragleave', () => {
zone.classList.remove('drag-over');
});
zone.addEventListener('drop', (e) => {
e.preventDefault();
zone.classList.remove('drag-over');
const files = e.dataTransfer.files;
if (files.length > 0) {
handleFileSelect(files[0]);
}
});
zone.addEventListener('click', () => {
if (zone === dropZone) fileInput.click();
else fileInputDecrypt.click();
});
});
fileInput.addEventListener('change', (e) => {
if (e.target.files.length > 0) handleFileSelect(e.target.files[0]);
});
fileInputDecrypt.addEventListener('change', (e) => {
if (e.target.files.length > 0) handleFileSelect(e.target.files[0]);
});
function handleFileSelect(file) {
selectedFile = file;
const info = currentOperation === 'decrypt' ? 'fileInfoDecrypt' : 'fileInfo';
const name = currentOperation === 'decrypt' ? 'fileNameDecrypt' : 'fileName';
const size = currentOperation === 'decrypt' ? 'fileSizeDecrypt' : 'fileSize';
document.getElementById(info).classList.remove('hidden');
document.getElementById(name).textContent = file.name;
document.getElementById(size).textContent = formatBytes(file.size);
}
function formatBytes(bytes) {
if (bytes === 0) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
function showError(msg) {
errorLog.textContent = msg;
errorLog.classList.remove('hidden');
console.error(msg);
}
function updateProgress(processed, total, startTime) {
const percent = Math.floor((processed / total) * 100);
progressBarFill.style.width = `${percent}%`;
percentText.textContent = `${percent}%`;
const elapsed = (Date.now() - startTime) / 1000;
if (elapsed > 0) {
const speed = processed / elapsed;
speedText.textContent = `${formatBytes(speed)}/s`;
const remaining = total - processed;
const eta = remaining / speed;
etaText.textContent = `ETA: ${formatTime(eta)}`;
}
}
function formatTime(seconds) {
if (!isFinite(seconds) || seconds < 0) return '--:--';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
const s = Math.floor(seconds % 60);
return [h, m, s].map(v => v.toString().padStart(2, '0')).filter((v, i) => v !== '00' || i > 0).join(':');
}
// --- Cryptography Functions ---
/**
* SECURITY NOTES:
*
* 1. PBKDF2 for Key Derivation:
* We use PBKDF2 with SHA-256 and 310,000 iterations. This is a recommended
* configuration to protect against brute-force attacks on the password.
* A 16-byte random salt ensures that identical passwords result in different keys.
*
* 2. HKDF for Sub-key Expansion:
* We derive a master key via PBKDF2 and then use HKDF to expand it into an
* encryption key. This is a best practice for key separation, allowing for
* future expansion (e.g., adding a separate MAC key or metadata key).
*
* 3. AES-GCM for Authenticated Encryption:
* AES-GCM provides both confidentiality and integrity. Each 4MiB chunk is
* independently authenticated. If a single byte of ciphertext or the tag
* is modified, decryption of that chunk will fail.
*
* 4. Per-chunk IV Uniqueness:
* Each chunk must have a unique IV (Initialization Vector) to be secure in GCM mode.
* We use a 12-byte IV where the last 4 bytes are a counter (big-endian).
* IV = ivBase[0..7] | (ivBase[8..11] + chunkIndex).
* This ensures that even if the same plaintext appears in different chunks,
* the ciphertext will be different.
*
* 5. Integrity Verification:
* While a global HMAC was considered, it is omitted due to WebCrypto's lack
* of streaming HMAC support without 3rd party libs. We rely on AES-GCM's
* per-chunk authentication. Decryption stops immediately if any chunk
* fails authentication, preventing the use of corrupted data.
*/
/**
* Derives a master key from a password using PBKDF2.
*/
async function deriveMasterKey(password, salt) {
const encoder = new TextEncoder();
const baseKey = await crypto.subtle.importKey(
"raw",
encoder.encode(password),
"PBKDF2",
false,
["deriveBits", "deriveKey"]
);
const derivedBits = await crypto.subtle.deriveBits(
{
name: "PBKDF2",
salt: salt,
iterations: PBKDF2_ITERATIONS,
hash: "SHA-256"
},
baseKey,
256
);
return crypto.subtle.importKey(
"raw",
derivedBits,
"HKDF",
false,
["deriveKey"]
);
}
/**
* Derives an encryption key from the master key using HKDF.
*/
async function deriveEncryptionKey(masterKey) {
return crypto.subtle.deriveKey(
{
name: "HKDF",
hash: "SHA-256",
salt: new Uint8Array(0), // No extra salt for HKDF
info: new TextEncoder().encode("encryption")
},
masterKey,
{ name: "AES-GCM", length: 256 },
false,
["encrypt", "decrypt"]
);
}
/**
* Generates a unique IV for a specific chunk.
* IV = ivBase (12 bytes) with the last 4 bytes as big-endian uint32 counter + chunkIndex.
*/
function getChunkIV(ivBase, chunkIndex) {
const iv = new Uint8Array(ivBase);
const view = new DataView(iv.buffer, iv.byteOffset, iv.byteLength);
// Get the last 4 bytes as uint32 (big-endian)
const baseCounter = view.getUint32(8, false);
// Add chunkIndex and keep it within 32 bits
const newCounter = (baseCounter + chunkIndex) >>> 0;
view.setUint32(8, newCounter, false);
return iv;
}
/**
* Encrypts a single chunk.
*/
async function encryptChunk(chunk, key, iv) {
return crypto.subtle.encrypt(
{ name: "AES-GCM", iv: iv },
key,
chunk
);
}
/**
* Decrypts a single chunk.
*/
async function decryptChunk(chunk, key, iv) {
try {
return await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: iv },
key,
chunk
);
} catch (e) {
throw new Error("Decryption failed. Wrong password or corrupted file.");
}
}
// --- Binary Format ---
/**
* Creates the file header as an ArrayBuffer.
*/
function createHeader(salt, ivBase, totalSize, filename) {
const encoder = new TextEncoder();
const filenameBytes = encoder.encode(filename);
// Calculate total header size
// magic(4) + v(1) + kdf(1) + iter(4) + saltLen(1) + salt(16) + chunkS(4) + totalS(8) + ivBaseL(1) + ivBase(12) + fileNL(2) + fileN(?)
const headerSize = 4 + 1 + 1 + 4 + 1 + 16 + 4 + 8 + 1 + 12 + 2 + filenameBytes.length;
const buffer = new ArrayBuffer(headerSize);
const view = new DataView(buffer);
let offset = 0;
// magic: "FENC"
for (let i = 0; i < 4; i++) {
view.setUint8(offset++, MAGIC.charCodeAt(i));
}
view.setUint8(offset++, VERSION);
view.setUint8(offset++, KDF_PBKDF2);
view.setUint32(offset, PBKDF2_ITERATIONS, false); offset += 4;
view.setUint8(offset++, SALT_LEN);
new Uint8Array(buffer, offset, SALT_LEN).set(salt); offset += SALT_LEN;
view.setUint32(offset, CHUNK_SIZE, false); offset += 4;
view.setBigUint64(offset, BigInt(totalSize), true); offset += 8; // little-endian
view.setUint8(offset++, IV_BASE_LEN);
new Uint8Array(buffer, offset, IV_BASE_LEN).set(ivBase); offset += IV_BASE_LEN;
view.setUint16(offset, filenameBytes.length, true); offset += 2; // little-endian
new Uint8Array(buffer, offset, filenameBytes.length).set(filenameBytes);
return buffer;
}
/**
* Parses the file header from a Blob/File.
*/
async function parseHeader(file) {
// Read enough for a reasonable header (max filename 64KB)
// Minimal header is around 54 bytes + filename.
// Let's read first 4KB to be safe.
const initialSize = 4096;
const initialBuffer = await file.slice(0, initialSize).arrayBuffer();
const view = new DataView(initialBuffer);
let offset = 0;
// magic
const magic = String.fromCharCode(view.getUint8(0), view.getUint8(1), view.getUint8(2), view.getUint8(3));
if (magic !== MAGIC) throw new Error("Not a SecureStream file.");
offset += 4;
const version = view.getUint8(offset++);
if (version !== VERSION) throw new Error(`Unsupported version: ${version}`);
const kdf = view.getUint8(offset++);
if (kdf !== KDF_PBKDF2) throw new Error(`Unsupported KDF: ${kdf}`);
const iterations = view.getUint32(offset, false); offset += 4;
if (iterations !== PBKDF2_ITERATIONS) {
console.warn(`Iterations mismatch: file has ${iterations}, expected ${PBKDF2_ITERATIONS}`);
}
const saltLen = view.getUint8(offset++);
const salt = new Uint8Array(initialBuffer.slice(offset, offset + saltLen)); offset += saltLen;
const chunkSize = view.getUint32(offset, false); offset += 4;
const totalSize = Number(view.getBigUint64(offset, true)); offset += 8;
const ivBaseLen = view.getUint8(offset++);
const ivBase = new Uint8Array(initialBuffer.slice(offset, offset + ivBaseLen)); offset += ivBaseLen;
const filenameLen = view.getUint16(offset, true); offset += 2;
// If filename goes beyond 1KB, we'd need to read more, but 1KB is plenty for most filenames.
const filenameBytes = new Uint8Array(initialBuffer.slice(offset, offset + filenameLen));
const filename = new TextDecoder().decode(filenameBytes);
offset += filenameLen;
return {
salt,
chunkSize,
totalSize,
ivBase,
filename,
headerSize: offset
};
}
/**
* Creates a chunk prefix: [chunkPlainLen(4)][chunkCipherLen(4)]
*/
function createChunkPrefix(plainLen, cipherLen) {
const buffer = new ArrayBuffer(8);
const view = new DataView(buffer);
view.setUint32(0, plainLen, false);
view.setUint32(4, cipherLen, false);
return buffer;
}
/**
* Creates the file footer as an ArrayBuffer.
*/
function createFooter() {
const buffer = new ArrayBuffer(1 + 2);
const view = new DataView(buffer);
view.setUint8(0, MAC_NONE);
view.setUint16(1, 0, true);
return buffer;
}
// --- Streaming Output ---
/**
* Gets a WritableStream for saving the file.
* Uses File System Access API if available, otherwise falls back to Service Worker streaming.
*/
async function getWritableStream(filename, size) {
if ('showSaveFilePicker' in window) {
try {
const handle = await window.showSaveFilePicker({
suggestedName: filename,
});
return await handle.createWritable();
} catch (e) {
if (e.name === 'AbortError') return null;
throw e;
}
}
// Fallback to Service Worker streaming
if (!('serviceWorker' in navigator) || !navigator.serviceWorker.controller) {
throw new Error("Streaming download not supported in this browser (Service Worker not active).");
}
const { port1, port2 } = new MessageChannel();
const downloadPromise = new Promise((resolve) => {
port1.onmessage = (event) => {
if (event.data.downloadUrl) {
// Trigger download
const a = document.createElement('a');
a.href = event.data.downloadUrl;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
resolve();
}
};
});
navigator.serviceWorker.controller.postMessage({
action: 'stream-download',
filename: filename,
streamPort: port2
}, [port2]);
await downloadPromise;
// Return a shim for WritableStream that sends data to the Service Worker
return {
async write(chunk) {
port1.postMessage({ action: 'data', chunk }, [chunk instanceof ArrayBuffer ? chunk : chunk.buffer]);
},
async close() {
port1.postMessage({ action: 'end' });
},
async abort(err) {
port1.postMessage({ action: 'error', error: err.message });
}
};
}
// --- UI Helpers ---
function setStatus(text) {
statusText.textContent = text;
}
function showProgress() {
progressContainer.classList.remove('hidden');
encryptBtn.disabled = true;
decryptBtn.disabled = true;
}
function hideProgress() {
progressContainer.classList.add('hidden');
encryptBtn.disabled = false;
decryptBtn.disabled = false;
}
const cancelController = {
aborted: false,
abort() { this.aborted = true; }
};
document.getElementById('cancelBtn').addEventListener('click', () => {
cancelController.abort();
setStatus("Cancelled.");
});
// --- Main Flows ---
async function encryptFlow() {
errorLog.classList.add('hidden');
if (!selectedFile) return showError("Please select a file.");
const password = document.getElementById('password').value;
const confirm = document.getElementById('confirmPassword').value;
if (!password) return showError("Please enter a password.");
if (password !== confirm) return showError("Passwords do not match.");
cancelController.aborted = false;
showProgress();
setStatus("Initializing...");
try {
const salt = crypto.getRandomValues(new Uint8Array(SALT_LEN));
const ivBase = crypto.getRandomValues(new Uint8Array(IV_BASE_LEN));
const masterKey = await deriveMasterKey(password, salt);
const encKey = await deriveEncryptionKey(masterKey);
const header = createHeader(salt, ivBase, selectedFile.size, selectedFile.name);
const writer = await getWritableStream(selectedFile.name + ".enc", header.byteLength + selectedFile.size + 1024);
if (!writer) {
hideProgress();
return;
}
await writer.write(header);
const startTime = Date.now();
let processed = 0;
let chunkIndex = 0;
while (processed < selectedFile.size) {
if (cancelController.aborted) {
await writer.abort(new Error("User cancelled"));
return;
}
const end = Math.min(processed + CHUNK_SIZE, selectedFile.size);
const chunk = await selectedFile.slice(processed, end).arrayBuffer();
const plainLen = chunk.byteLength;
const iv = getChunkIV(ivBase, chunkIndex);
const encrypted = await encryptChunk(chunk, encKey, iv);
const cipherLen = encrypted.byteLength;
const prefix = createChunkPrefix(plainLen, cipherLen);
await writer.write(prefix);
await writer.write(encrypted);
processed = end;
chunkIndex++;
updateProgress(processed, selectedFile.size, startTime);
setStatus(`Encrypting chunk ${chunkIndex}...`);
// Yield to UI
await new Promise(r => setTimeout(r, 0));
}
const footer = createFooter();
await writer.write(footer);
await writer.close();
setStatus("Encryption complete!");
} catch (e) {
showError("Encryption failed: " + e.message);
} finally {
encryptBtn.disabled = false;
decryptBtn.disabled = false;
}
}
async function decryptFlow() {
errorLog.classList.add('hidden');
if (!selectedFile) return showError("Please select a file.");
const password = document.getElementById('passwordDecrypt').value;
if (!password) return showError("Please enter password.");
cancelController.aborted = false;
showProgress();
setStatus("Parsing header...");
try {
const headerInfo = await parseHeader(selectedFile);
const masterKey = await deriveMasterKey(password, headerInfo.salt);
const encKey = await deriveEncryptionKey(masterKey);
const writer = await getWritableStream(headerInfo.filename, headerInfo.totalSize);
if (!writer) {
hideProgress();
return;
}
const startTime = Date.now();
let offset = headerInfo.headerSize;
let processed = 0;
let chunkIndex = 0;
while (processed < headerInfo.totalSize) {
if (cancelController.aborted) {
await writer.abort(new Error("User cancelled"));
return;
}
// Read chunk prefix (8 bytes)
const prefixBuffer = await selectedFile.slice(offset, offset + 8).arrayBuffer();
if (prefixBuffer.byteLength < 8) break; // End of chunks
const view = new DataView(prefixBuffer);
const plainLen = view.getUint32(0, false);
const cipherLen = view.getUint32(4, false);
offset += 8;
// Read encrypted chunk
const encrypted = await selectedFile.slice(offset, offset + cipherLen).arrayBuffer();
if (encrypted.byteLength < cipherLen) throw new Error("File truncated.");
offset += cipherLen;
const iv = getChunkIV(headerInfo.ivBase, chunkIndex);
const decrypted = await decryptChunk(encrypted, encKey, iv);
await writer.write(decrypted);
processed += plainLen;
chunkIndex++;
updateProgress(processed, headerInfo.totalSize, startTime);
setStatus(`Decrypting chunk ${chunkIndex}...`);
// Yield to UI
await new Promise(r => setTimeout(r, 0));
}
await writer.close();
setStatus("Decryption complete!");
} catch (e) {
showError("Decryption failed: " + e.message);
} finally {
encryptBtn.disabled = false;
decryptBtn.disabled = false;
}
}
encryptBtn.addEventListener('click', encryptFlow);
decryptBtn.addEventListener('click', decryptFlow);
// --- Self-Test Harness ---
async function computeHash(buffer) {
const hashBuffer = await crypto.subtle.digest('SHA-256', buffer);
return Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
async function runSelfTest() {
const testResult = document.getElementById('testResult');
testResult.textContent = "Running 20MB self-test...";
testResult.style.color = "inherit";
try {
const testSize = 20 * 1024 * 1024;
const testData = new Uint8Array(testSize);
// crypto.getRandomValues has a 64KB limit per call
for (let i = 0; i < testSize; i += 65536) {
const size = Math.min(65536, testSize - i);
crypto.getRandomValues(new Uint8Array(testData.buffer, i, size));
}
const originalHash = await computeHash(testData);
const password = "TestPassword123!";
const salt = crypto.getRandomValues(new Uint8Array(SALT_LEN));
const ivBase = crypto.getRandomValues(new Uint8Array(IV_BASE_LEN));
const masterKey = await deriveMasterKey(password, salt);
const encKey = await deriveEncryptionKey(masterKey);
// Encryption
const chunks = [];
let processed = 0;
let chunkIndex = 0;
while (processed < testSize) {
const end = Math.min(processed + CHUNK_SIZE, testSize);
const chunk = testData.slice(processed, end);
const iv = getChunkIV(ivBase, chunkIndex);
const encrypted = await encryptChunk(chunk, encKey, iv);
const prefix = createChunkPrefix(chunk.byteLength, encrypted.byteLength);
chunks.push(prefix, encrypted);
processed = end;
chunkIndex++;
}
const encryptedBlob = new Blob(chunks);
// Decryption
const decryptedChunks = [];
processed = 0;
chunkIndex = 0;
const encryptedArrayBuffer = await encryptedBlob.arrayBuffer();
let offset = 0;
while (offset < encryptedArrayBuffer.byteLength) {
const view = new DataView(encryptedArrayBuffer, offset, 8);
const plainLen = view.getUint32(0, false);
const cipherLen = view.getUint32(4, false);
offset += 8;
const encryptedChunk = encryptedArrayBuffer.slice(offset, offset + cipherLen);
offset += cipherLen;
const iv = getChunkIV(ivBase, chunkIndex);
const decrypted = await decryptChunk(encryptedChunk, encKey, iv);
decryptedChunks.push(decrypted);
chunkIndex++;
}
const decryptedBlob = new Blob(decryptedChunks);
const decryptedArrayBuffer = await decryptedBlob.arrayBuffer();
const decryptedHash = await computeHash(decryptedArrayBuffer);
if (originalHash === decryptedHash) {
testResult.textContent = "Self-test PASSED (SHA-256 matched)";
testResult.style.color = "green";
} else {
testResult.textContent = "Self-test FAILED (Hash mismatch)";
testResult.style.color = "red";
}
} catch (e) {
testResult.textContent = "Self-test ERROR: " + e.message;
testResult.style.color = "red";
}
}
document.getElementById('runTestBtn').addEventListener('click', runSelfTest);