-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
1313 lines (1124 loc) · 54.2 KB
/
Copy pathscript.js
File metadata and controls
1313 lines (1124 loc) · 54.2 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
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
document.addEventListener('DOMContentLoaded', () => {
// --- Card Click Handlers for Home Page ---
const classicalCiphersCard = document.getElementById('classical-ciphers-card');
const streamBlockCiphersCard = document.getElementById('stream-block-ciphers-card');
const asymmetricEncryptionCard = document.getElementById('asymmetric-encryption-card');
const hashFunctionsCard = document.getElementById('hash-functions-card');
if (classicalCiphersCard) {
classicalCiphersCard.addEventListener('click', () => {
window.location.href = 'classical-ciphers.html'; // Redirect to classical-ciphers.html
});
}
// Add similar listeners for other cards when you have their target pages
if (streamBlockCiphersCard) {
streamBlockCiphersCard.addEventListener('click', () => {
console.log("Clicked Stream & Block Ciphers. (Page not yet defined)");
window.location.href = 'stream-block-ciphers.html'; // Uncomment when page exists
});
}
if (asymmetricEncryptionCard) {
asymmetricEncryptionCard.addEventListener('click', () => {
console.log("Clicked Asymmetric Encryption. (Page not yet defined)");
window.location.href = 'asymmetric-encryption.html'; // Uncomment when page exists
});
}
if (hashFunctionsCard) {
hashFunctionsCard.addEventListener('click', () => {
console.log("Clicked Hash Functions. (Page not yet defined)");
window.location.href = 'hash-functions.html'; // Uncomment when page exists
});
}
const caesarCipherCard = document.getElementById('caesar-cipher-card');
if (caesarCipherCard) {
console.log("Caesar Cipher card element found on classical-ciphers.html!"); // DEBUG LOG
caesarCipherCard.addEventListener('click', () => {
console.log("Caesar Cipher card CLICKED! Navigating to caesar-cipher.html"); // DEBUG LOG
window.location.href = 'caesar-cipher.html';
});
}
const vigenereCipherCard = document.getElementById('vigenere-cipher-card');
if (vigenereCipherCard) {
vigenereCipherCard.addEventListener('click', () => {
window.location.href = 'vigenere-cipher.html';
});
}
// Corrected Rail Fence Cipher Card Handler
const railFenceCipherCard = document.getElementById('rail-fence-cipher-card');
if (railFenceCipherCard) {
railFenceCipherCard.addEventListener('click', () => { // <--- ADD THIS ADDEVENTLISTENER
window.location.href = 'rail-fence-cipher.html';
}); // <--- ADD THIS CLOSING CURLY BRACE AND PARENTHESIS
}
const playfairCipherCard = document.getElementById('playfair-cipher-card');
if (playfairCipherCard) {
playfairCipherCard.addEventListener('click', () => {
console.log("Playfair Cipher card CLICKED! (Page not yet created)");
window.location.href = 'playfair-cipher.html'; // Uncomment when you create this page
});
}
const aesCipherCard = document.getElementById('aes-cipher-card');
if (aesCipherCard) {
aesCipherCard.addEventListener('click', () => {
window.location.href = 'aes-cipher.html'; // Redirect to aes-cipher.html
});
}
const rc4CipherCard = document.getElementById('rc4-cipher-card');
if (rc4CipherCard) {
rc4CipherCard.addEventListener('click', () => {
alert("RC4 is a stream cipher, but it's largely considered insecure for new applications due to known vulnerabilities.");
// You can uncomment the line below if you create a specific page for RC4:
window.location.href = 'rc4-cipher.html';
});
}
const desCipherCard = document.getElementById('des-cipher-card');
if (desCipherCard) {
desCipherCard.addEventListener('click', () => {
alert("DES is an older block cipher and is considered insecure due to its small key size. It has been replaced by AES.");
// You can uncomment the line below if you create a specific page for DES:
window.location.href = 'des-cipher.html';
});
}
// --- Home Icon Functionality ---
// If you want the home icon on the main page to refresh or simply stay
// On classical-ciphers.html, the home icon is already an <a> tag linking to index.html
const homeIcon = document.querySelector('.home-icon-link'); // Target the link wrapper if it exists
if (homeIcon && window.location.pathname.endsWith('/index.html') || window.location.pathname === '/') {
// If on the index page, clicking home icon could refresh or just log
homeIcon.addEventListener('click', (event) => {
event.preventDefault(); // Prevent default link behavior if you want custom action
console.log("Home icon clicked on main page.");
// Or if you want it to explicitly reload the home page:
// window.location.href = 'index.html';
});
}
// --- Search Bar Functionality (Basic Example) ---
const searchInput = document.querySelector('.search-bar input');
const searchIcon = document.querySelector('.search-bar .search-icon');
if (searchIcon && searchInput) {
searchIcon.addEventListener('click', () => {
performSearch(searchInput.value);
});
searchInput.addEventListener('keypress', (event) => {
if (event.key === 'Enter') {
performSearch(searchInput.value);
}
});
}
function performSearch(query) {
if (query.trim() !== '') {
console.log(`Searching for: ${query}`);
// Here you would implement actual search logic:
// - Redirect to a search results page: window.location.href = `search.html?query=${encodeURIComponent(query)}`;
// - Filter content on the current page (more complex JS)
alert(`Performing search for: "${query}"`); // For demonstration
} else {
console.log("Search query is empty.");
}
}
// --- Cipher-Specific Logic (Caesar Cipher Example) ---
// This logic will only run if we are on the caesar-cipher.html page
if (window.location.pathname.includes('caesar-cipher.html')) {
const inputText = document.getElementById('inputText');
const caesarKey = document.getElementById('caesarKey');
const encryptBtn = document.getElementById('encryptBtn');
const decryptBtn = document.getElementById('decryptBtn');
const outputText = document.getElementById('outputText');
encryptBtn.addEventListener('click', () => {
const text = inputText.value;
const shift = parseInt(caesarKey.value);
if (isNaN(shift) || shift < 1 || shift > 25) {
alert("Please enter a valid shift key between 1 and 25.");
return;
}
outputText.value = caesarEncrypt(text, shift);
});
decryptBtn.addEventListener('click', () => {
const text = inputText.value;
const shift = parseInt(caesarKey.value);
if (isNaN(shift) || shift < 1 || shift > 25) {
alert("Please enter a valid shift key between 1 and 25.");
return;
}
outputText.value = caesarDecrypt(text, shift);
});
function caesarEncrypt(text, shift) {
let result = '';
for (let i = 0; i < text.length; i++) {
let char = text.charCodeAt(i);
if (char >= 65 && char <= 90) { // Uppercase letters (A-Z)
result += String.fromCharCode(((char - 65 + shift) % 26) + 65);
} else if (char >= 97 && char <= 122) { // Lowercase letters (a-z)
result += String.fromCharCode(((char - 97 + shift) % 26) + 97);
} else { // Non-alphabetic characters
result += text[i];
}
}
return result;
}
function caesarDecrypt(text, shift) {
// Decrypting is simply encrypting with a negative shift (or 26 - shift)
return caesarEncrypt(text, (26 - shift) % 26);
}
}
if (window.location.pathname.includes('vigenere-cipher.html')) {
const inputText = document.getElementById('inputText');
const vigenereKeyInput = document.getElementById('vigenereKey'); // Changed ID to match HTML
const encryptBtn = document.getElementById('encryptBtn');
const decryptBtn = document.getElementById('decryptBtn');
const outputText = document.getElementById('outputText');
encryptBtn.addEventListener('click', () => {
const text = inputText.value;
const keyword = vigenereKeyInput.value;
outputText.value = vigenereEncrypt(text, keyword);
});
decryptBtn.addEventListener('click', () => {
const text = inputText.value;
const keyword = vigenereKeyInput.value;
outputText.value = vigenereDecrypt(text, keyword);
});
function vigenereEncrypt(text, keyword) {
let result = '';
keyword = keyword.toUpperCase().replace(/[^A-Z]/g, ''); // Clean and uppercase keyword
if (keyword.length === 0) {
alert("Please enter a valid keyword.");
return text;
}
let keywordIndex = 0;
for (let i = 0; i < text.length; i++) {
let char = text.charCodeAt(i);
let encryptedChar = char;
if (char >= 65 && char <= 90) { // Uppercase
let keyShift = keyword.charCodeAt(keywordIndex % keyword.length) - 65;
encryptedChar = ((char - 65 + keyShift) % 26) + 65;
keywordIndex++;
} else if (char >= 97 && char <= 122) { // Lowercase
let keyShift = keyword.charCodeAt(keywordIndex % keyword.length) - 65;
encryptedChar = ((char - 97 + keyShift) % 26) + 97;
keywordIndex++;
}
result += String.fromCharCode(encryptedChar);
}
return result;
}
function vigenereDecrypt(text, keyword) {
let result = '';
keyword = keyword.toUpperCase().replace(/[^A-Z]/g, ''); // Clean and uppercase keyword
if (keyword.length === 0) {
alert("Please enter a valid keyword.");
return text;
}
let keywordIndex = 0;
for (let i = 0; i < text.length; i++) {
let char = text.charCodeAt(i);
let decryptedChar = char;
if (char >= 65 && char <= 90) { // Uppercase
let keyShift = keyword.charCodeAt(keywordIndex % keyword.length) - 65;
decryptedChar = ((char - 65 - keyShift + 26) % 26) + 65; // Add 26 for negative results
keywordIndex++;
} else if (char >= 97 && char <= 122) { // Lowercase
let keyShift = keyword.charCodeAt(keywordIndex % keyword.length) - 65;
decryptedChar = ((char - 97 - keyShift + 26) % 26) + 97; // Add 26 for negative results
keywordIndex++;
}
result += String.fromCharCode(decryptedChar);
}
return result;
}
}
if (window.location.pathname.includes('rail-fence-cipher.html')) {
const inputText = document.getElementById('inputText');
const railsKeyInput = document.getElementById('railsKey');
const encryptBtn = document.getElementById('encryptBtn');
const decryptBtn = document.getElementById('decryptBtn');
const outputText = document.getElementById('outputText');
encryptBtn.addEventListener('click', () => {
const text = inputText.value;
const rails = parseInt(railsKeyInput.value);
if (isNaN(rails) || rails < 2) {
alert("Please enter a valid number of rails (2 or more).");
return;
}
outputText.value = railFenceEncrypt(text, rails);
});
decryptBtn.addEventListener('click', () => {
const text = inputText.value;
const rails = parseInt(railsKeyInput.value);
if (isNaN(rails) || rails < 2) {
alert("Please enter a valid number of rails (2 or more).");
return;
}
outputText.value = railFenceDecrypt(text, rails);
});
function railFenceEncrypt(text, rails) {
if (rails === 1 || text.length === 0) return text;
const fence = Array.from({ length: rails }, () => []);
let rail = 0;
let direction = 1; // 1 for down, -1 for up
for (let i = 0; i < text.length; i++) {
fence[rail].push(text[i]);
rail += direction;
if (rail === rails - 1 || rail === 0) {
direction *= -1; // Reverse direction
}
}
return fence.map(r => r.join('')).join('');
}
function railFenceDecrypt(text, rails) {
if (rails === 1 || text.length === 0) return text;
const len = text.length;
const fence = Array.from({ length: rails }, () => []);
const decrypted = new Array(len);
let rail = 0;
let direction = 1;
// Mark positions where chars would go in the fence
const positions = Array.from({ length: rails }, () => []);
for (let i = 0; i < len; i++) {
positions[rail].push(i);
rail += direction;
if (rail === rails - 1 || rail === 0) {
direction *= -1;
}
}
// Fill the fence with characters from the ciphertext
let charIndex = 0;
for (let r = 0; r < rails; r++) {
for (let c = 0; c < positions[r].length; c++) {
fence[r].push(text[charIndex++]);
}
}
// Reconstruct the plaintext by going back through the zigzag pattern
rail = 0;
direction = 1;
for (let i = 0; i < len; i++) {
// Get the character from the correct position in the current rail's queue
decrypted[positions[rail][0]] = fence[rail].shift();
rail += direction;
if (rail === rails - 1 || rail === 0) {
direction *= -1;
}
}
return decrypted.join('');
}
}
if (window.location.pathname.includes('playfair-cipher.html')) {
const inputText = document.getElementById('inputText');
const playfairKeyInput = document.getElementById('playfairKey');
const encryptBtn = document.getElementById('encryptBtn');
const decryptBtn = document.getElementById('decryptBtn');
const outputText = document.getElementById('outputText');
let playfairSquare = []; // Store the 5x5 key square
// Function to build the 5x5 Playfair key square
function buildPlayfairSquare(keyword) {
const alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"; // Note: J is omitted, treated as I
let key = keyword.toUpperCase().replace(/J/g, 'I').replace(/[^A-Z]/g, ''); // Clean keyword, replace J with I
let uniqueKey = '';
// Get unique characters from keyword
for (let char of key) {
if (uniqueKey.indexOf(char) === -1) {
uniqueKey += char;
}
}
let combinedString = uniqueKey + alphabet;
let squareChars = '';
for (let char of combinedString) {
if (squareChars.indexOf(char) === -1) {
squareChars += char;
}
}
playfairSquare = [];
for (let i = 0; i < 5; i++) {
playfairSquare.push(squareChars.substring(i * 5, (i * 5) + 5).split(''));
}
}
// Function to find the row and column of a character in the square
function findChar(char) {
char = char.toUpperCase();
if (char === 'J') char = 'I'; // Treat J as I
for (let r = 0; r < 5; r++) {
for (let c = 0; c < 5; c++) {
if (playfairSquare[r][c] === char) {
return { row: r, col: c };
}
}
}
return null; // Should not happen with valid input
}
// Function to prepare plaintext (remove non-alphabetic, replace J, handle double letters and odd length)
function preparePlayfairText(text) {
text = text.toUpperCase().replace(/J/g, 'I').replace(/[^A-Z]/g, '');
let preparedText = '';
for (let i = 0; i < text.length; i++) {
preparedText += text[i];
if (i + 1 < text.length && text[i] === text[i + 1]) {
preparedText += 'X'; // Insert 'X' for double letters
}
}
if (preparedText.length % 2 !== 0) {
preparedText += 'X'; // Pad with 'X' if odd length
}
return preparedText;
}
// Playfair Encryption Logic
function playfairEncrypt(text, keyword) {
buildPlayfairSquare(keyword);
if (playfairSquare.length === 0 || playfairSquare[0].length === 0) {
alert("Invalid keyword for Playfair cipher.");
return "";
}
let preparedText = preparePlayfairText(text);
let ciphertext = '';
for (let i = 0; i < preparedText.length; i += 2) {
let char1 = preparedText[i];
let char2 = preparedText[i + 1];
let pos1 = findChar(char1);
let pos2 = findChar(char2);
if (!pos1 || !pos2) { // Should not happen if preparePlayfairText is correct
ciphertext += char1 + char2;
continue;
}
// Same row
if (pos1.row === pos2.row) {
ciphertext += playfairSquare[pos1.row][(pos1.col + 1) % 5];
ciphertext += playfairSquare[pos2.row][(pos2.col + 1) % 5];
}
// Same column
else if (pos1.col === pos2.col) {
ciphertext += playfairSquare[(pos1.row + 1) % 5][pos1.col];
ciphertext += playfairSquare[(pos2.row + 1) % 5][pos2.col];
}
// Different row and column (rectangle)
else {
ciphertext += playfairSquare[pos1.row][pos2.col];
ciphertext += playfairSquare[pos2.row][pos1.col];
}
}
return ciphertext;
}
// Playfair Decryption Logic
function playfairDecrypt(text, keyword) {
buildPlayfairSquare(keyword);
if (playfairSquare.length === 0 || playfairSquare[0].length === 0) {
alert("Invalid keyword for Playfair cipher.");
return "";
}
// Decryption requires cleaning, but not padding or inserting X for doubles
let preparedText = text.toUpperCase().replace(/J/g, 'I').replace(/[^A-Z]/g, '');
if (preparedText.length % 2 !== 0) {
alert("Ciphertext length must be even for Playfair decryption.");
return "";
}
let plaintext = '';
for (let i = 0; i < preparedText.length; i += 2) {
let char1 = preparedText[i];
let char2 = preparedText[i + 1];
let pos1 = findChar(char1);
let pos2 = findChar(char2);
if (!pos1 || !pos2) {
plaintext += char1 + char2;
continue;
}
// Same row
if (pos1.row === pos2.row) {
plaintext += playfairSquare[pos1.row][(pos1.col - 1 + 5) % 5];
plaintext += playfairSquare[pos2.row][(pos2.col - 1 + 5) % 5];
}
// Same column
else if (pos1.col === pos2.col) {
plaintext += playfairSquare[(pos1.row - 1 + 5) % 5][pos1.col];
plaintext += playfairSquare[(pos2.row - 1 + 5) % 5][pos2.col];
}
// Different row and column (rectangle)
else {
plaintext += playfairSquare[pos1.row][pos2.col];
plaintext += playfairSquare[pos2.row][pos1.col];
}
}
// Optional: Remove padding 'X' and inserted 'X's if they weren't part of original plaintext
// This can be complex and may require user discretion. For simplicity, we'll return raw.
return plaintext;
}
// Event listeners for the Playfair tool buttons
encryptBtn.addEventListener('click', () => {
const text = inputText.value;
const keyword = playfairKeyInput.value;
if (!keyword.trim()) {
alert("Please enter a keyword for Playfair cipher.");
return;
}
outputText.value = playfairEncrypt(text, keyword);
});
decryptBtn.addEventListener('click', () => {
const text = inputText.value;
const keyword = playfairKeyInput.value;
if (!keyword.trim()) {
alert("Please enter a keyword for Playfair cipher.");
return;
}
outputText.value = playfairDecrypt(text, keyword);
});
}
// --- Helper functions for ArrayBuffer to Base64/String conversion ---
// These functions are generally useful for Web Crypto API interactions.
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function base64ToArrayBuffer(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;
}
function stringToArrayBuffer(str) {
return new TextEncoder().encode(str).buffer;
}
function arrayBufferToString(buffer) {
return new TextDecoder().decode(buffer);
}
// --- AES Cipher-Specific Logic (ADD THIS NEW BLOCK) ---
// This logic will only run if we are on the aes-cipher.html page
if (window.location.pathname.includes('aes-cipher.html')) {
const inputText = document.getElementById('inputText');
const aesKeyInput = document.getElementById('aesKey');
const aesIVInput = document.getElementById('aesIV');
const generateKeyBtn = document.getElementById('generateKeyBtn');
const generateIVBtn = document.getElementById('generateIVBtn');
const encryptBtn = document.getElementById('encryptBtn');
const decryptBtn = document.getElementById('decryptBtn');
const outputText = document.getElementById('outputText');
// Generate a random AES-256 key (256 bits = 32 bytes)
generateKeyBtn.addEventListener('click', async () => {
try {
const key = await crypto.subtle.generateKey(
{
name: "AES-GCM",
length: 256, // 128, 192, or 256 bits
},
true, // whether the key is extractable (i.e. can be used in exportKey)
["encrypt", "decrypt"] // can be used for these operations
);
const exportedKey = await crypto.subtle.exportKey("raw", key);
aesKeyInput.value = arrayBufferToBase64(exportedKey);
} catch (error) {
console.error("Error generating key:", error);
alert("Error generating key. Check console for details.");
}
});
// Generate a random 12-byte IV (for AES-GCM)
generateIVBtn.addEventListener('click', () => {
const iv = crypto.getRandomValues(new Uint8Array(12)); // 96-bit IV is standard for GCM
aesIVInput.value = arrayBufferToBase64(iv.buffer);
});
// Encrypt functionality
encryptBtn.addEventListener('click', async () => {
try {
const text = inputText.value;
const base64Key = aesKeyInput.value;
const base64IV = aesIVInput.value;
if (!text || !base64Key || !base64IV) {
alert("Please enter text, key, and IV.");
return;
}
const keyBuffer = base64ToArrayBuffer(base64Key);
const ivBuffer = base64ToArrayBuffer(base64IV);
const textBuffer = stringToArrayBuffer(text);
const importedKey = await crypto.subtle.importKey(
"raw",
keyBuffer,
{ name: "AES-GCM" },
true,
["encrypt"]
);
const encryptedBuffer = await crypto.subtle.encrypt(
{
name: "AES-GCM",
iv: ivBuffer,
},
importedKey,
textBuffer
);
outputText.value = arrayBufferToBase64(encryptedBuffer);
} catch (error) {
console.error("Encryption error:", error);
alert("Encryption failed. Make sure key/IV are valid Base64 and correct length. Check console for details.");
}
});
// Decrypt functionality
decryptBtn.addEventListener('click', async () => {
try {
const base64Ciphertext = inputText.value;
const base64Key = aesKeyInput.value;
const base64IV = aesIVInput.value;
if (!base64Ciphertext || !base64Key || !base64IV) {
alert("Please enter ciphertext, key, and IV.");
return;
}
// --- ADD THESE CONSOLE.LOGS FOR DEBUGGING ---
console.log("Decrypting...");
console.log("Input Ciphertext (Base64):", base64Ciphertext);
console.log("Input Key (Base64):", base64Key);
console.log("Input IV (Base64):", base64IV);
// --- END DEBUG LOGS ---
const keyBuffer = base64ToArrayBuffer(base64Key);
const ivBuffer = base64ToArrayBuffer(base64IV);
const ciphertextBuffer = base64ToArrayBuffer(base64Ciphertext);
// --- ADD THESE CONSOLE.LOGS FOR BUFFER SIZES ---
console.log("Key Buffer Length (bytes):", keyBuffer.byteLength);
console.log("IV Buffer Length (bytes):", ivBuffer.byteLength);
console.log("Ciphertext Buffer Length (bytes):", ciphertextBuffer.byteLength);
// --- END DEBUG LOGS ---
const importedKey = await crypto.subtle.importKey(
"raw",
keyBuffer,
{ name: "AES-GCM" },
true,
["decrypt"]
);
const decryptedBuffer = await crypto.subtle.decrypt(
{
name: "AES-GCM",
iv: ivBuffer,
},
importedKey,
ciphertextBuffer
);
outputText.value = arrayBufferToString(decryptedBuffer);
} catch (error) {
console.error("Decryption error:", error);
alert("Decryption failed. Make sure key/IV are valid Base64 and correct length, and ciphertext is correct. Check console for details.");
}
});
}
if (window.location.pathname.includes('rc4-cipher.html')) {
// Get HTML elements (RC4 specific)
const plaintextInput = document.getElementById('plaintextInput');
const encryptionKeyInput = document.getElementById('encryptionKey');
const encryptButton = document.getElementById('encryptButton');
const outputCiphertext = document.getElementById('outputCiphertext');
const ciphertextInput = document.getElementById('ciphertextInput');
const decryptionKeyInput = document.getElementById('decryptionKey');
const decryptButton = document.getElementById('decryptButton');
const outputDecryptedText = document.getElementById('outputDecryptedText');
/**
* RC4 Key Scheduling Algorithm (KSA)
* Initializes the S-box based on the key.
* @param {Uint8Array} key - The key as a byte array.
* @returns {Uint8Array} The initialized S-box.
*/
function rc4KSA(key) {
let S = new Uint8Array(256);
for (let i = 0; i < 256; i++) {
S[i] = i;
}
let j = 0;
for (let i = 0; i < 256; i++) {
j = (j + S[i] + key[i % key.length]) % 256;
// Swap S[i] and S[j]
[S[i], S[j]] = [S[j], S[i]];
}
return S;
}
/**
* RC4 Pseudo-Random Generation Algorithm (PRGA)
* Generates a keystream byte.
* @param {Uint8Array} S - The initialized S-box.
* @param {{i: number, j: number}} state - Current state of i and j.
* @returns {{keystreamByte: number, i: number, j: number}} The generated byte and updated state.
*/
function rc4PRGA(S, state) {
let i = state.i;
let j = state.j;
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap S[i] and S[j]
[S[i], S[j]] = [S[j], S[i]];
let t = (S[i] + S[j]) % 256;
let keystreamByte = S[t];
return { keystreamByte, i, j };
}
/**
* RC4 encryption/decryption function.
* Since RC4 is a stream cipher (XORing plaintext with keystream),
* the same function is used for encryption and decryption.
* @param {string} inputString - The plaintext or ciphertext string.
* @param {string} keyString - The key string.
* @returns {Uint8Array} The resulting byte array.
*/
function rc4(inputString, keyString) {
const inputBytes = new TextEncoder().encode(inputString);
const keyBytes = new TextEncoder().encode(keyString);
if (keyBytes.length === 0) {
throw new Error("Key cannot be empty for RC4.");
}
let S = rc4KSA(keyBytes);
let i = 0;
let j = 0;
let outputBytes = new Uint8Array(inputBytes.length);
for (let k = 0; k < inputBytes.length; k++) {
({ keystreamByte: outputBytes[k], i, j } = rc4PRGA(S, { i, j }));
outputBytes[k] ^= inputBytes[k]; // XOR with keystream
}
return outputBytes;
}
// --- Event Listeners for RC4 ---
encryptButton.addEventListener('click', () => {
const plaintext = plaintextInput.value;
const key = encryptionKeyInput.value;
if (!plaintext || !key) {
alert('Please enter both plaintext and a key for encryption.');
return;
}
try {
const encryptedBytes = rc4(plaintext, key);
outputCiphertext.value = arrayBufferToBase64(encryptedBytes); // Reuse your existing helper
} catch (error) {
console.error("RC4 Encryption error:", error);
alert("Encryption failed: " + error.message);
}
});
decryptButton.addEventListener('click', () => {
const ciphertextBase64 = ciphertextInput.value;
const key = decryptionKeyInput.value;
if (!ciphertextBase64 || !key) {
alert('Please enter both ciphertext and a key for decryption.');
return;
}
try {
// Decode Base64 ciphertext into bytes
const decodedBytes = new Uint8Array(base64ToArrayBuffer(ciphertextBase64));
// To decrypt with RC4, you apply the 'rc4' function again with the *same key*.
// The rc4 function expects a string input, so we convert decodedBytes back to a string.
// This string is then passed to rc4 to generate the keystream and XOR it.
const intermediateString = new TextDecoder().decode(decodedBytes); // This assumes the ciphertext bytes can be meaningfully decoded to a string for the RC4 function's input parameter.
const decryptedBytes = rc4(intermediateString, key); // Apply RC4 (which also decrypts)
outputDecryptedText.value = new TextDecoder().decode(decryptedBytes);
} catch (error) {
console.error("RC4 Decryption error:", error);
alert("Decryption failed. Make sure key is correct and ciphertext is valid Base64. Check console for details.");
}
});
}
// --- END OF NEW RC4 CIPHER LOGIC ---
// DES Cipher Logic
if (window.location.pathname.includes('des-cipher.html')) {
const plaintextInput = document.getElementById('desPlaintextInput');
const encryptionKeyInput = document.getElementById('desEncryptionKey');
const encryptionIVInput = document.getElementById('desEncryptionIV');
const encryptButton = document.getElementById('desEncryptButton');
const outputCiphertext = document.getElementById('desOutputCiphertext');
const ciphertextInput = document.getElementById('desCiphertextInput');
const decryptionKeyInput = document.getElementById('desDecryptionKey');
const decryptionIVInput = document.getElementById('desDecryptionIV');
const decryptButton = document.getElementById('desDecryptButton');
const outputDecryptedText = document.getElementById('desOutputDecryptedText');
// Helper function for Base64 encoding (from your existing script.js)
// Ensure arrayBufferToBase64 and base64ToArrayBuffer are accessible here if they're not global
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
function base64ToArrayBuffer(base64) {
const binary_string = window.atob(base64);
const len = binary_string.length;
const bytes = new Uint8Array(len);
for (let i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes.buffer;
}
// DES Encryption
encryptButton.addEventListener('click', () => {
const plaintext = plaintextInput.value;
const key = encryptionKeyInput.value;
const iv = encryptionIVInput.value;
if (!plaintext || !key || !iv) {
alert('Please enter plaintext, key, and IV for encryption.');
return;
}
if (key.length !== 8) {
alert('DES Key must be exactly 8 characters long.');
return;
}
if (iv.length !== 8) {
alert('DES IV must be exactly 8 characters long.');
return;
}
try {
// Convert key and IV strings to WordArrays for CryptoJS
const parsedKey = CryptoJS.enc.Utf8.parse(key);
const parsedIV = CryptoJS.enc.Utf8.parse(iv);
// Encrypt using DES with CBC mode (default for CryptoJS DES)
const encrypted = CryptoJS.DES.encrypt(plaintext, parsedKey, {
iv: parsedIV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
// Output Base64 encoded ciphertext
outputCiphertext.value = encrypted.toString();
} catch (error) {
console.error("DES Encryption error:", error);
alert("Encryption failed: " + error.message);
}
});
// DES Decryption
decryptButton.addEventListener('click', () => {
const ciphertextBase64 = ciphertextInput.value;
const key = decryptionKeyInput.value;
const iv = decryptionIVInput.value;
if (!ciphertextBase64 || !key || !iv) {
alert('Please enter ciphertext, key, and IV for decryption.');
return;
}
if (key.length !== 8) {
alert('DES Key must be exactly 8 characters long.');
return;
}
if (iv.length !== 8) {
alert('DES IV must be exactly 8 characters long.');
return;
}
try {
// Convert key and IV strings to WordArrays for CryptoJS
const parsedKey = CryptoJS.enc.Utf8.parse(key);
const parsedIV = CryptoJS.enc.Utf8.parse(iv);
// Decrypt
const decrypted = CryptoJS.DES.decrypt(ciphertextBase64, parsedKey, {
iv: parsedIV,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
});
// Convert decrypted WordArray to UTF-8 string
outputDecryptedText.value = decrypted.toString(CryptoJS.enc.Utf8);
} catch (error) {
console.error("DES Decryption error:", error);
alert("Decryption failed. Make sure key/IV are correct and ciphertext is valid Base64. Check console for details.");
}
});
}
// Hash Functions Logic
if (window.location.pathname.includes('hash-functions.html')) {
const hashInput = document.getElementById('hashInput');
const md5Button = document.getElementById('md5Button');
const md5Output = document.getElementById('md5Output');
const sha1Button = document.getElementById('sha1Button');
const sha1Output = document.getElementById('sha1Output');
const sha256Button = document.getElementById('sha256Button');
const sha256Output = document.getElementById('sha256Output');
const sha512Button = document.getElementById('sha512Button');
const sha512Output = document.getElementById('sha512Output');
// MD5 Hash Calculation
md5Button.addEventListener('click', () => {
const input = hashInput.value;
if (!input) {
alert('Please enter text to hash.');
return;
}
try {
const hash = CryptoJS.MD5(input);
md5Output.value = hash.toString(CryptoJS.enc.Hex);
} catch (error) {
console.error("MD5 Hashing error:", error);
alert("MD5 Hashing failed: " + error.message);
}
});
// SHA-1 Hash Calculation
sha1Button.addEventListener('click', () => {
const input = hashInput.value;
if (!input) {
alert('Please enter text to hash.');
return;
}
try {
const hash = CryptoJS.SHA1(input);
sha1Output.value = hash.toString(CryptoJS.enc.Hex);
} catch (error) {
console.error("SHA-1 Hashing error:", error);
alert("SHA-1 Hashing failed: " + error.message);
}
});
// SHA-256 Hash Calculation
sha256Button.addEventListener('click', () => {
const input = hashInput.value;
if (!input) {
alert('Please enter text to hash.');
return;
}
try {
const hash = CryptoJS.SHA256(input);
sha256Output.value = hash.toString(CryptoJS.enc.Hex);
} catch (error) {
console.error("SHA-256 Hashing error:", error);
alert("SHA-256 Hashing failed: " + error.message);
}
});
// SHA-512 Hash Calculation
sha512Button.addEventListener('click', () => {
const input = hashInput.value;