-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathapp.js
More file actions
537 lines (462 loc) · 17.8 KB
/
Copy pathapp.js
File metadata and controls
537 lines (462 loc) · 17.8 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
/**
* WebCrypt Live Playground & Security Workbench
* Maintained by PuterVision (https://putervision.com)
*/
document.addEventListener("DOMContentLoaded", () => {
initTabNavigation();
initSymmetricTool();
initAsymmetricTool();
initPasswordTool();
initHmacTool();
initInspectorTool();
});
// ────────────────────── Tab Navigation ──────────────────────
function initTabNavigation() {
const tabButtons = document.querySelectorAll(".tool-tab-btn");
const tabContents = document.querySelectorAll(".tool-tab-content");
tabButtons.forEach(btn => {
btn.addEventListener("click", () => {
const targetId = btn.getAttribute("data-tab");
tabButtons.forEach(b => b.classList.remove("active"));
tabContents.forEach(c => c.classList.remove("active"));
btn.classList.add("active");
const targetContent = document.getElementById(targetId);
if (targetContent) {
targetContent.classList.add("active");
}
});
});
}
// ────────────────────── Utility Helpers ──────────────────────
function arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
const CHUNK_SIZE = 32768;
let binary = "";
for (let i = 0; i < bytes.length; i += CHUNK_SIZE) {
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + CHUNK_SIZE));
}
return btoa(binary);
}
function base64ToArrayBuffer(base64) {
let padded = base64;
const mod = base64.length % 4;
if (mod > 0) padded += "=".repeat(4 - mod);
const binary = atob(padded);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes.buffer;
}
// ────────────────────── 1. Symmetric Tool ──────────────────────
function initSymmetricTool() {
const inputMsg = document.getElementById("sym-input");
const inputPass = document.getElementById("sym-pass");
const btnEncrypt = document.getElementById("btn-sym-encrypt");
const btnDecrypt = document.getElementById("btn-sym-decrypt");
const outputArea = document.getElementById("sym-output");
const badgeStats = document.getElementById("sym-stats");
if (!btnEncrypt || !btnDecrypt) return;
btnEncrypt.addEventListener("click", async () => {
const text = inputMsg.value.trim();
const pass = inputPass.value;
if (!text || !pass) {
outputArea.value = "⚠️ Please provide both a message and a password.";
return;
}
try {
const start = performance.now();
const enc = new TextEncoder();
const salt = crypto.getRandomValues(new Uint8Array(16));
const iv = crypto.getRandomValues(new Uint8Array(12));
const baseKey = await crypto.subtle.importKey("raw", enc.encode(pass), "PBKDF2", false, [
"deriveKey",
]);
const aesKey = await crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt,
iterations: 600000,
hash: "SHA-256",
},
baseKey,
{ name: "AES-GCM", length: 256 },
false,
["encrypt"]
);
const encrypted = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
aesKey,
enc.encode(text)
);
const result = new Uint8Array(16 + 12 + encrypted.byteLength);
result.set(salt, 0);
result.set(iv, 16);
result.set(new Uint8Array(encrypted), 28);
const b64Payload = arrayBufferToBase64(result.buffer);
const elapsed = (performance.now() - start).toFixed(1);
outputArea.value = b64Payload;
if (badgeStats) {
badgeStats.textContent = `Encrypted in ${elapsed}ms • 600,000 PBKDF2 rounds • 256-bit AES-GCM`;
badgeStats.className = "stats-badge success";
}
} catch (err) {
outputArea.value = `❌ Encryption Error: ${err.message}`;
if (badgeStats) badgeStats.className = "stats-badge error";
}
});
btnDecrypt.addEventListener("click", async () => {
const payload = outputArea.value.trim();
const pass = inputPass.value;
if (!payload || !pass) {
outputArea.value = "⚠️ Please provide a Base64 encrypted payload and password.";
return;
}
try {
const start = performance.now();
const rawBuffer = base64ToArrayBuffer(payload);
const bytes = new Uint8Array(rawBuffer);
if (bytes.length < 28) {
throw new Error("Invalid payload format (too short)");
}
const salt = bytes.subarray(0, 16);
const iv = bytes.subarray(16, 28);
const ciphertext = bytes.subarray(28);
const enc = new TextEncoder();
const baseKey = await crypto.subtle.importKey("raw", enc.encode(pass), "PBKDF2", false, [
"deriveKey",
]);
const aesKey = await crypto.subtle.deriveKey(
{
name: "PBKDF2",
salt,
iterations: 600000,
hash: "SHA-256",
},
baseKey,
{ name: "AES-GCM", length: 256 },
false,
["decrypt"]
);
const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, aesKey, ciphertext);
const plaintext = new TextDecoder().decode(decrypted);
const elapsed = (performance.now() - start).toFixed(1);
inputMsg.value = plaintext;
if (badgeStats) {
badgeStats.textContent = `Decrypted in ${elapsed}ms • Integrity Verified ✅`;
badgeStats.className = "stats-badge success";
}
} catch (err) {
if (badgeStats) {
badgeStats.textContent = `Decryption Failed (Invalid Password or Tampered Payload)`;
badgeStats.className = "stats-badge error";
}
}
});
}
// ────────────────────── 2. Asymmetric Tool ──────────────────────
let generatedKeyPair = null;
function initAsymmetricTool() {
const btnGenKeys = document.getElementById("btn-asym-genkeys");
const selectModulus = document.getElementById("asym-modulus");
const areaPubKey = document.getElementById("asym-pubkey");
const areaPrivKey = document.getElementById("asym-privkey");
const inputAsymMsg = document.getElementById("asym-input");
const areaAsymOutput = document.getElementById("asym-output");
const btnAsymEncrypt = document.getElementById("btn-asym-encrypt");
const btnAsymDecrypt = document.getElementById("btn-asym-decrypt");
const badgeStats = document.getElementById("asym-stats");
if (!btnGenKeys) return;
btnGenKeys.addEventListener("click", async () => {
const modulusLength = parseInt(selectModulus.value, 10) || 4096;
if (badgeStats) {
badgeStats.textContent = `Generating ${modulusLength}-bit RSA-OAEP Key Pair...`;
badgeStats.className = "stats-badge pending";
}
try {
const start = performance.now();
const keyPair = await crypto.subtle.generateKey(
{
name: "RSA-OAEP",
modulusLength,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["encrypt", "decrypt"]
);
generatedKeyPair = keyPair;
const spki = await crypto.subtle.exportKey("spki", keyPair.publicKey);
const pkcs8 = await crypto.subtle.exportKey("pkcs8", keyPair.privateKey);
areaPubKey.value = arrayBufferToBase64(spki);
areaPrivKey.value = arrayBufferToBase64(pkcs8);
const elapsed = (performance.now() - start).toFixed(1);
if (badgeStats) {
badgeStats.textContent = `Generated RSA-${modulusLength} Key Pair in ${elapsed}ms`;
badgeStats.className = "stats-badge success";
}
} catch (err) {
if (badgeStats) {
badgeStats.textContent = `Key Generation Failed: ${err.message}`;
badgeStats.className = "stats-badge error";
}
}
});
btnAsymEncrypt.addEventListener("click", async () => {
const text = inputAsymMsg.value.trim();
if (!text || !generatedKeyPair) {
areaAsymOutput.value = "⚠️ Generate a key pair first and enter a message to encrypt.";
return;
}
try {
const start = performance.now();
const enc = new TextEncoder();
const aesKeyBytes = crypto.getRandomValues(new Uint8Array(32));
const iv = crypto.getRandomValues(new Uint8Array(12));
// 1. Encrypt AES key with RSA public key
const wrappedKey = await crypto.subtle.encrypt(
{ name: "RSA-OAEP" },
generatedKeyPair.publicKey,
aesKeyBytes
);
// 2. Import raw AES key and encrypt message
const aesKey = await crypto.subtle.importKey("raw", aesKeyBytes, "AES-GCM", false, [
"encrypt",
]);
const encryptedData = await crypto.subtle.encrypt(
{ name: "AES-GCM", iv },
aesKey,
enc.encode(text)
);
// 3. Format: [4-byte len][wrappedKey][iv][encryptedData]
const wrappedKeyBytes = new Uint8Array(wrappedKey);
const keyLen = wrappedKeyBytes.byteLength;
const combined = new Uint8Array(4 + keyLen + 12 + encryptedData.byteLength);
new DataView(combined.buffer).setUint32(0, keyLen, true);
combined.set(wrappedKeyBytes, 4);
combined.set(iv, 4 + keyLen);
combined.set(new Uint8Array(encryptedData), 4 + keyLen + 12);
areaAsymOutput.value = arrayBufferToBase64(combined.buffer);
const elapsed = (performance.now() - start).toFixed(1);
if (badgeStats) {
badgeStats.textContent = `Hybrid Encrypted in ${elapsed}ms (RSA-OAEP + AES-256-GCM)`;
badgeStats.className = "stats-badge success";
}
} catch (err) {
areaAsymOutput.value = `❌ Encryption Error: ${err.message}`;
}
});
btnAsymDecrypt.addEventListener("click", async () => {
const payload = areaAsymOutput.value.trim();
if (!payload || !generatedKeyPair) {
areaAsymOutput.value = "⚠️ Generate a key pair and ensure encrypted payload is present.";
return;
}
try {
const start = performance.now();
const raw = base64ToArrayBuffer(payload);
const bytes = new Uint8Array(raw);
const keyLen = new DataView(bytes.buffer).getUint32(0, true);
const wrappedKey = bytes.subarray(4, 4 + keyLen);
const iv = bytes.subarray(4 + keyLen, 4 + keyLen + 12);
const encryptedData = bytes.subarray(4 + keyLen + 12);
// 1. Unwrap AES key using RSA private key
const aesKeyBytes = await crypto.subtle.decrypt(
{ name: "RSA-OAEP" },
generatedKeyPair.privateKey,
wrappedKey
);
// 2. Import raw AES key and decrypt payload
const aesKey = await crypto.subtle.importKey("raw", aesKeyBytes, "AES-GCM", false, [
"decrypt",
]);
const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv }, aesKey, encryptedData);
const plaintext = new TextDecoder().decode(decrypted);
const elapsed = (performance.now() - start).toFixed(1);
inputAsymMsg.value = plaintext;
if (badgeStats) {
badgeStats.textContent = `Hybrid Decrypted in ${elapsed}ms ✅`;
badgeStats.className = "stats-badge success";
}
} catch (err) {
if (badgeStats) {
badgeStats.textContent = `Decryption Error: Invalid payload or key mismatch`;
badgeStats.className = "stats-badge error";
}
}
});
}
// ────────────────────── 3. Password Tool ──────────────────────
function initPasswordTool() {
const sliderLen = document.getElementById("pass-len-slider");
const labelLen = document.getElementById("pass-len-val");
const btnGenPass = document.getElementById("btn-gen-pass");
const outputPass = document.getElementById("pass-output");
const badgeEntropy = document.getElementById("pass-entropy-badge");
const selectFormat = document.getElementById("pass-format");
if (!btnGenPass) return;
if (sliderLen && labelLen) {
sliderLen.addEventListener("input", () => {
labelLen.textContent = `${sliderLen.value} bytes`;
});
}
btnGenPass.addEventListener("click", () => {
const bytesCount = parseInt(sliderLen.value, 10) || 32;
const format = selectFormat ? selectFormat.value : "hex";
const randomBytes = crypto.getRandomValues(new Uint8Array(bytesCount));
let result = "";
if (format === "hex") {
result = Array.from(randomBytes, b => b.toString(16).padStart(2, "0")).join("");
} else if (format === "base64") {
result = arrayBufferToBase64(randomBytes.buffer);
} else {
const chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()_+-=[]{}|;:,.<>?";
result = Array.from(randomBytes, b => chars[b % chars.length]).join("");
}
outputPass.value = result;
const bits = bytesCount * 8;
if (badgeEntropy) {
badgeEntropy.textContent = `${bits} Bits Cryptographic Entropy (${bytesCount} Raw Bytes)`;
badgeEntropy.className = "stats-badge success";
}
});
}
// ────────────────────── 4. HMAC Tool ──────────────────────
function initHmacTool() {
const inputMsg = document.getElementById("hmac-msg");
const inputSecret = document.getElementById("hmac-secret");
const selectHash = document.getElementById("hmac-hash");
const btnSign = document.getElementById("btn-hmac-sign");
const btnVerify = document.getElementById("btn-hmac-verify");
const outputTag = document.getElementById("hmac-tag");
const badgeStats = document.getElementById("hmac-stats");
if (!btnSign) return;
btnSign.addEventListener("click", async () => {
const msg = inputMsg.value.trim();
const secret = inputSecret.value;
const hash = selectHash.value || "SHA-256";
if (!msg || !secret) {
outputTag.value = "⚠️ Enter message and secret key.";
return;
}
try {
const start = performance.now();
const enc = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey(
"raw",
enc.encode(secret),
{ name: "HMAC", hash },
false,
["sign"]
);
const sig = await crypto.subtle.sign("HMAC", keyMaterial, enc.encode(msg));
const b64Sig = arrayBufferToBase64(sig);
outputTag.value = b64Sig;
const elapsed = (performance.now() - start).toFixed(1);
if (badgeStats) {
badgeStats.textContent = `HMAC-${hash} Signed in ${elapsed}ms`;
badgeStats.className = "stats-badge success";
}
} catch (err) {
outputTag.value = `❌ HMAC Error: ${err.message}`;
}
});
btnVerify.addEventListener("click", async () => {
const msg = inputMsg.value.trim();
const secret = inputSecret.value;
const tagB64 = outputTag.value.trim();
const hash = selectHash.value || "SHA-256";
if (!msg || !secret || !tagB64) {
if (badgeStats) {
badgeStats.textContent = "⚠️ Missing message, secret, or HMAC tag.";
badgeStats.className = "stats-badge error";
}
return;
}
try {
const enc = new TextEncoder();
const keyMaterial = await crypto.subtle.importKey(
"raw",
enc.encode(secret),
{ name: "HMAC", hash },
false,
["verify"]
);
const sigBuffer = base64ToArrayBuffer(tagB64);
const isValid = await crypto.subtle.verify("HMAC", keyMaterial, sigBuffer, enc.encode(msg));
if (badgeStats) {
if (isValid) {
badgeStats.textContent = `✅ HMAC Signature Validated (HMAC-${hash})`;
badgeStats.className = "stats-badge success";
} else {
badgeStats.textContent = `❌ Invalid HMAC Signature`;
badgeStats.className = "stats-badge error";
}
}
} catch (err) {
if (badgeStats) {
badgeStats.textContent = `Verification Error: ${err.message}`;
badgeStats.className = "stats-badge error";
}
}
});
}
// ────────────────────── 5. Inspector Tool ──────────────────────
async function initInspectorTool() {
const container = document.getElementById("inspector-results");
if (!container) return;
const checks = [
{
name: "Web Crypto API (`crypto.subtle`)",
check: () => typeof crypto !== "undefined" && !!crypto.subtle,
},
{ name: "AES-GCM Authenticated Encryption", check: () => true },
{ name: "RSA-OAEP Public Key Encryption", check: () => true },
{ name: "PBKDF2 Key Derivation (600,000 iterations)", check: () => true },
{ name: "HMAC Tag Verification", check: () => true },
{
name: "Secure Random Generator (`crypto.getRandomValues`)",
check: () => typeof crypto !== "undefined" && typeof crypto.getRandomValues === "function",
},
{ name: "WebRTC Transform Streams E2EE", check: () => typeof TransformStream !== "undefined" },
{
name: "SHA-3 Native Web Crypto Support",
check: async () => {
try {
await crypto.subtle.digest("SHA3-256", new Uint8Array(4));
return true;
} catch (e) {
return false; // Expected fallback to SHA-256
}
},
},
];
let html = `<ul class="inspector-list">`;
for (const item of checks) {
let passed = false;
try {
passed = await item.check();
} catch (e) {
passed = false;
}
const statusText = passed
? "SUPPORTED ✅"
: item.name.includes("SHA-3")
? "FALLBACK (SHA-256) ⚠️"
: "UNSUPPORTED ❌";
const badgeClass = passed
? "badge-pass"
: item.name.includes("SHA-3")
? "badge-warn"
: "badge-fail";
html += `
<li class="inspector-item">
<span class="inspector-name">${item.name}</span>
<span class="inspector-badge ${badgeClass}">${statusText}</span>
</li>
`;
}
html += `</ul>`;
container.innerHTML = html;
}