-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
576 lines (487 loc) · 15.6 KB
/
app.js
File metadata and controls
576 lines (487 loc) · 15.6 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
/**
* CryptoVault - Advanced Text Encryption Application
* Supports AES-256, DES, and RSA-2048 encryption algorithms
* Features glassmorphism UI with light/dark mode
*/
// ==================== STATE MANAGEMENT ====================
const appState = {
currentAlgorithm: 'aes',
theme: 'light',
keys: {
aes: null,
des: null,
rsa: { public: null, private: null }
},
inputText: '',
resultText: '',
encryptionTime: 0
};
// ==================== ALGORITHM METADATA ====================
const algorithmData = {
aes: {
name: 'AES-256',
fullName: 'Advanced Encryption Standard',
keyLength: '256 bits',
security: 'High',
color: '#2196F3'
},
des: {
name: 'DES',
fullName: 'Data Encryption Standard',
keyLength: '56 bits',
security: 'Low (Deprecated)',
color: '#FF9800'
},
rsa: {
name: 'RSA-2048',
fullName: 'Rivest-Shamir-Adleman',
keyLength: '2048 bits',
security: 'High',
color: '#4CAF50'
}
};
// ==================== DOM ELEMENTS ====================
const elements = {
themeToggle: document.getElementById('themeToggle'),
algoTabs: document.querySelectorAll('.algo-tab'),
inputText: document.getElementById('inputText'),
charCount: document.getElementById('charCount'),
generateKeysBtn: document.getElementById('generateKeys'),
encryptBtn: document.getElementById('encryptBtn'),
decryptBtn: document.getElementById('decryptBtn'),
keyDisplay: document.getElementById('keyDisplay'),
resultSection: document.getElementById('resultSection'),
resultText: document.getElementById('resultText'),
resultMetadata: document.getElementById('resultMetadata'),
copyBtn: document.getElementById('copyBtn'),
downloadBtn: document.getElementById('downloadBtn'),
toast: document.getElementById('toast'),
toastIcon: document.getElementById('toastIcon'),
toastMessage: document.getElementById('toastMessage'),
loadingOverlay: document.getElementById('loadingOverlay'),
currentAlgo: document.getElementById('currentAlgo'),
keyLength: document.getElementById('keyLength'),
encryptionTime: document.getElementById('encryptionTime'),
securityLevel: document.getElementById('securityLevel')
};
// ==================== INITIALIZATION ====================
function init() {
// Set default theme (in-memory only)
setTheme('light');
// Generate initial keys
generateKeys();
// Update metrics display
updateMetrics();
// Setup event listeners
setupEventListeners();
}
// ==================== EVENT LISTENERS ====================
function setupEventListeners() {
// Theme toggle
elements.themeToggle.addEventListener('click', toggleTheme);
// Algorithm tabs
elements.algoTabs.forEach(tab => {
tab.addEventListener('click', () => {
const algo = tab.dataset.algo;
selectAlgorithm(algo);
});
});
// Input text
elements.inputText.addEventListener('input', (e) => {
appState.inputText = e.target.value;
elements.charCount.textContent = `${e.target.value.length} characters`;
});
// Buttons
elements.generateKeysBtn.addEventListener('click', generateKeys);
elements.encryptBtn.addEventListener('click', encryptText);
elements.decryptBtn.addEventListener('click', decryptText);
elements.copyBtn.addEventListener('click', copyToClipboard);
elements.downloadBtn.addEventListener('click', downloadResult);
}
// ==================== THEME MANAGEMENT ====================
function toggleTheme() {
const newTheme = appState.theme === 'light' ? 'dark' : 'light';
setTheme(newTheme);
}
function setTheme(theme) {
appState.theme = theme;
document.documentElement.setAttribute('data-theme', theme);
}
// ==================== ALGORITHM SELECTION ====================
function selectAlgorithm(algo) {
appState.currentAlgorithm = algo;
// Update active tab
elements.algoTabs.forEach(tab => {
tab.classList.toggle('active', tab.dataset.algo === algo);
});
// Update metrics
updateMetrics();
// Update key display
displayKeys();
// Hide result section
elements.resultSection.classList.add('hidden');
}
// ==================== METRICS UPDATE ====================
function updateMetrics() {
const algo = algorithmData[appState.currentAlgorithm];
elements.currentAlgo.textContent = algo.name;
elements.keyLength.textContent = algo.keyLength;
// Update security badge
const badge = elements.securityLevel.querySelector('.security-badge');
if (algo.security.includes('High')) {
badge.className = 'security-badge high';
badge.textContent = 'High';
} else {
badge.className = 'security-badge low';
badge.textContent = 'Low';
}
}
// ==================== KEY GENERATION ====================
function generateKeys() {
showLoading();
// Generate keys based on current algorithm
setTimeout(() => {
switch(appState.currentAlgorithm) {
case 'aes':
generateAESKey();
break;
case 'des':
generateDESKey();
break;
case 'rsa':
generateRSAKeys();
break;
}
displayKeys();
hideLoading();
showToast('Keys generated successfully!', 'success');
}, 500);
}
function generateAESKey() {
// Generate random 256-bit key
const array = new Uint8Array(32);
crypto.getRandomValues(array);
appState.keys.aes = arrayToHex(array);
}
function generateDESKey() {
// Generate random 64-bit key (8 bytes)
const array = new Uint8Array(8);
crypto.getRandomValues(array);
appState.keys.des = arrayToHex(array);
}
function generateRSAKeys() {
// Generate RSA key pair using JSEncrypt
const crypt = new JSEncrypt({default_key_size: 2048});
appState.keys.rsa.public = crypt.getPublicKey();
appState.keys.rsa.private = crypt.getPrivateKey();
}
// ==================== KEY DISPLAY ====================
function displayKeys() {
const algo = appState.currentAlgorithm;
let html = '';
switch(algo) {
case 'aes':
html = createKeyItem('AES Key', appState.keys.aes, 'aes-key');
break;
case 'des':
html = createKeyItem('DES Key', appState.keys.des, 'des-key');
break;
case 'rsa':
html = createKeyItem('Public Key', appState.keys.rsa.public, 'rsa-public');
html += createKeyItem('Private Key', appState.keys.rsa.private, 'rsa-private');
break;
}
elements.keyDisplay.innerHTML = html;
// Setup key action buttons
setupKeyActions();
}
function createKeyItem(label, value, id) {
return `
<div class="key-item">
<span class="key-label">${label}</span>
<div class="key-value">
<span class="key-text" id="${id}">${truncateKey(value)}</span>
<div class="key-actions">
<button class="btn-icon-small" onclick="toggleKeyVisibility('${id}')" title="Toggle visibility">👁️</button>
<button class="btn-icon-small" onclick="copyKey('${id}')" title="Copy key">📋</button>
</div>
</div>
</div>
`;
}
function truncateKey(key) {
if (!key) return '';
if (key.length > 100) {
return key.substring(0, 50) + '...' + key.substring(key.length - 50);
}
return key;
}
function setupKeyActions() {
// Key actions are now inline onclick handlers
}
window.toggleKeyVisibility = function(id) {
const keyElement = document.getElementById(id);
keyElement.classList.toggle('hidden-key');
};
window.copyKey = function(id) {
const keyElement = document.getElementById(id);
const fullKey = getFullKey(id);
navigator.clipboard.writeText(fullKey).then(() => {
showToast('Key copied to clipboard!', 'success');
});
};
function getFullKey(id) {
switch(id) {
case 'aes-key':
return appState.keys.aes;
case 'des-key':
return appState.keys.des;
case 'rsa-public':
return appState.keys.rsa.public;
case 'rsa-private':
return appState.keys.rsa.private;
default:
return '';
}
}
// ==================== ENCRYPTION ====================
function encryptText() {
const text = appState.inputText.trim();
if (!text) {
showToast('Please enter text to encrypt', 'error');
return;
}
// RSA warning for large text
if (appState.currentAlgorithm === 'rsa' && text.length > 200) {
showToast('RSA is designed for small data. Consider using AES for large text.', 'error');
return;
}
showLoading();
setTimeout(() => {
try {
const startTime = performance.now();
let encrypted = '';
switch(appState.currentAlgorithm) {
case 'aes':
encrypted = encryptAES(text);
break;
case 'des':
encrypted = encryptDES(text);
break;
case 'rsa':
encrypted = encryptRSA(text);
break;
}
const endTime = performance.now();
appState.encryptionTime = (endTime - startTime).toFixed(2);
appState.resultText = encrypted;
displayResult(encrypted, 'Encrypted');
hideLoading();
showToast('Text encrypted successfully!', 'success');
} catch (error) {
hideLoading();
showToast('Encryption failed: ' + error.message, 'error');
console.error(error);
}
}, 300);
}
function encryptAES(text) {
// Using CryptoJS for AES encryption
const key = CryptoJS.enc.Hex.parse(appState.keys.aes);
const iv = CryptoJS.lib.WordArray.random(16);
const encrypted = CryptoJS.AES.encrypt(text, key, {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
// Combine IV and ciphertext
const combined = iv.concat(encrypted.ciphertext);
return combined.toString(CryptoJS.enc.Base64);
}
function encryptDES(text) {
// Using CryptoJS for DES encryption
const key = CryptoJS.enc.Hex.parse(appState.keys.des);
const encrypted = CryptoJS.DES.encrypt(text, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return encrypted.toString();
}
function encryptRSA(text) {
// Using JSEncrypt for RSA encryption
const encrypt = new JSEncrypt();
encrypt.setPublicKey(appState.keys.rsa.public);
const encrypted = encrypt.encrypt(text);
if (!encrypted) {
throw new Error('RSA encryption failed');
}
return encrypted;
}
// ==================== DECRYPTION ====================
function decryptText() {
const text = appState.inputText.trim();
if (!text) {
showToast('Please enter encrypted text to decrypt', 'error');
return;
}
showLoading();
setTimeout(() => {
try {
const startTime = performance.now();
let decrypted = '';
switch(appState.currentAlgorithm) {
case 'aes':
decrypted = decryptAES(text);
break;
case 'des':
decrypted = decryptDES(text);
break;
case 'rsa':
decrypted = decryptRSA(text);
break;
}
const endTime = performance.now();
appState.encryptionTime = (endTime - startTime).toFixed(2);
appState.resultText = decrypted;
displayResult(decrypted, 'Decrypted');
hideLoading();
showToast('Text decrypted successfully!', 'success');
} catch (error) {
hideLoading();
showToast('Decryption failed: ' + error.message, 'error');
console.error(error);
}
}, 300);
}
function decryptAES(ciphertext) {
try {
const combined = CryptoJS.enc.Base64.parse(ciphertext);
// Extract IV (first 16 bytes) and ciphertext
const iv = CryptoJS.lib.WordArray.create(combined.words.slice(0, 4));
const encrypted = CryptoJS.lib.WordArray.create(combined.words.slice(4));
const key = CryptoJS.enc.Hex.parse(appState.keys.aes);
const decrypted = CryptoJS.AES.decrypt(
{ ciphertext: encrypted },
key,
{
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
}
);
return decrypted.toString(CryptoJS.enc.Utf8);
} catch (error) {
throw new Error('Invalid ciphertext or key');
}
}
function decryptDES(ciphertext) {
try {
const key = CryptoJS.enc.Hex.parse(appState.keys.des);
const decrypted = CryptoJS.DES.decrypt(ciphertext, key, {
mode: CryptoJS.mode.ECB,
padding: CryptoJS.pad.Pkcs7
});
return decrypted.toString(CryptoJS.enc.Utf8);
} catch (error) {
throw new Error('Invalid ciphertext or key');
}
}
function decryptRSA(ciphertext) {
try {
const decrypt = new JSEncrypt();
decrypt.setPrivateKey(appState.keys.rsa.private);
const decrypted = decrypt.decrypt(ciphertext);
if (!decrypted) {
throw new Error('RSA decryption failed');
}
return decrypted;
} catch (error) {
throw new Error('Invalid ciphertext or private key');
}
}
// ==================== RESULT DISPLAY ====================
function displayResult(text, type) {
elements.resultText.textContent = text;
elements.resultSection.classList.remove('hidden');
// Update metadata
const algo = algorithmData[appState.currentAlgorithm];
elements.resultMetadata.innerHTML = `
<div class="metadata-item">
<span class="metadata-label">Type</span>
<span class="metadata-value">${type}</span>
</div>
<div class="metadata-item">
<span class="metadata-label">Algorithm</span>
<span class="metadata-value">${algo.name}</span>
</div>
<div class="metadata-item">
<span class="metadata-label">Time</span>
<span class="metadata-value">${appState.encryptionTime} ms</span>
</div>
<div class="metadata-item">
<span class="metadata-label">Length</span>
<span class="metadata-value">${text.length} chars</span>
</div>
`;
// Update encryption time in metrics
elements.encryptionTime.textContent = `${appState.encryptionTime} ms`;
// Scroll to result
elements.resultSection.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
}
// ==================== COPY TO CLIPBOARD ====================
function copyToClipboard() {
navigator.clipboard.writeText(appState.resultText).then(() => {
showToast('Copied to clipboard!', 'success');
}).catch(() => {
showToast('Failed to copy', 'error');
});
}
// ==================== DOWNLOAD RESULT ====================
function downloadResult() {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
const algo = algorithmData[appState.currentAlgorithm];
const filename = `encrypted_${appState.currentAlgorithm}_${timestamp}.txt`;
// Create file content with metadata
const content = `CryptoVault Encryption Output
${'='.repeat(50)}
Algorithm: ${algo.fullName}
Key Length: ${algo.keyLength}
Timestamp: ${new Date().toLocaleString()}
Encryption Time: ${appState.encryptionTime} ms
${'='.repeat(50)}
${appState.resultText}`;
// Create blob and download
const blob = new Blob([content], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
showToast('File downloaded successfully!', 'success');
}
// ==================== TOAST NOTIFICATION ====================
function showToast(message, type = 'success') {
elements.toast.className = `toast ${type}`;
elements.toastMessage.textContent = message;
elements.toastIcon.textContent = type === 'success' ? '✓' : '✗';
elements.toast.classList.remove('hidden');
setTimeout(() => {
elements.toast.classList.add('hidden');
}, 3000);
}
// ==================== LOADING OVERLAY ====================
function showLoading() {
elements.loadingOverlay.classList.remove('hidden');
}
function hideLoading() {
elements.loadingOverlay.classList.add('hidden');
}
// ==================== UTILITY FUNCTIONS ====================
function arrayToHex(array) {
return Array.from(array)
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}
// ==================== START APPLICATION ====================
document.addEventListener('DOMContentLoaded', init);