-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtughra.js
1422 lines (1304 loc) · 46.1 KB
/
tughra.js
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
/**
* The MIT License (MIT)
* Copyright (c) 2024 Mohanad Alkhatib
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
*
* Tughra Library
*
* This library provides a comprehensive framework for encrypting and decrypting text and files
* of various types using multiple algorithms, including Tughra, Caesar, Vigenère, and XOR. It is
* designed for developers and security professionals who need to secure sensitive information
* through encryption, as well as for educational purposes in understanding cryptographic concepts.
* The library aims to ensure data confidentiality and integrity by employing robust encryption
* techniques, making unauthorized access extremely difficult.
*
* End-to-End Encryption (E2EE):
* The Tughra Library implements End-to-End Encryption (E2EE) to ensure that sensitive information
* is securely transmitted from one party to another without any intermediaries being able to access
* the data. This encryption model guarantees that only the sender and intended recipient can decrypt
* the information, thereby enhancing privacy and data security. The use of strong encryption algorithms
* and unique keys for each transaction minimizes the risk of data breaches and unauthorized access,
* making it a reliable choice for secure communication.
*
* Note: The Tughra method is specifically designed to be unbreakable without the correct `keyOffsets`
* and the specified number of `cycles`. Attempting to decrypt without these parameters would require
* immense computational power and time, making brute-force attacks impractical.
*
* Use Cases:
* - **Secure Data Transmission**: Encrypt messages and files before sending them over insecure
* channels to protect sensitive information from eavesdroppers.
* - **Data Storage Security**: Encrypt data stored in databases or file systems to prevent
* unauthorized access and ensure data privacy.
* - **File Encryption**: Support for encrypting and decrypting files of all types, ensuring that
* sensitive documents are protected from unauthorized access.
* - **Educational Tool**: Demonstrate and explore cryptographic techniques and algorithms for
* learning purposes.
* - **Password Management**: Safely encrypt and store user passwords or sensitive credentials.
*
* Features:
* - **Key Offsets**: Users can specify unique key offsets that are used in the encryption/decryption
* process. These offsets determine how much each character in the input text is modified.
* - **Encryption Modes**: The library supports multiple algorithms:
* - **Tughra**: A custom encryption method.
* - **Caesar**: A classic cipher that shifts characters by a fixed number.
* - **Vigenère**: A method that uses a keyword to apply varying shifts to characters.
* - **XOR**: A simple cipher that applies the XOR operation with a given key.
* - **Base Encoding**: Users can enable or disable base encoding/decoding to handle the output of
* the encryption process.
* - **Key Strength Validation**: The library validates the strength of the provided encryption key,
* ensuring it meets minimum length requirements for security.
* - **File Support**: The library includes methods for encrypting and decrypting files of all types,
* allowing users to protect sensitive documents while maintaining usability.
*
* Usage:
* 1. Instantiate the Tughra class with the desired parameters:
* ```javascript
* const tughra = new Tughra(keyOffsets, mode, baseCharset, algorithm, encryptionKey);
* ```
* 2. Call the `process` method with the text to be encrypted or decrypted:
* ```javascript
* const result = tughra.process(text, cycles);
* ```
* 3. Utilize the `decryptFile` method to decrypt files:
* ```javascript
* const decryptedFile = tughra.decryptFile(filePath, cycles);
* ```
* 4. Utilize the `setAlgorithm` method to change the encryption algorithm if needed:
* ```javascript
* tughra.setAlgorithm('caesar');
* ```
*
* Class TughraLibrary:
*
* Contains predefined Unicode groups for generating character offsets from different languages
* and scripts. Each group is defined by its name and character range (start and end Unicode values).
*/
class Tughra {
constructor(mode, baseCharset, algorithm, encryptionKey = '', useBaseEncoding = false) {
// Ensure keyOffsets are unique and valid, then join them into a single string
const uniqueKeyOffsets = Array.from(new Set(encryptionKey)).map(item => {
const charCode = typeof item === 'string' ? item.charCodeAt(0) : item;
if (isNaN(charCode)) {
throw new Error("Invalid character in encryption array. Only letters and numbers are allowed.");
}
return item;
}).join(''); // Join characters into a single string without commas
if (algorithm === 'default' && uniqueKeyOffsets.length === 0) {
throw new Error("keyOffsets must contain at least one valid value.");
}
this.keyOffsets = uniqueKeyOffsets;
this.mode = mode || 'encrypt'; // 'encrypt' or 'decrypt', default = encrypt
this.useBaseEncoding = useBaseEncoding; // true for base encoding/decoding, false otherwise
this.baseCharset = baseCharset || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; // Base alphabet, default = Base64
this.baseLibrary = this.baseEncodeDecode(this.baseCharset); // Create base library
this.encryptionKey = new TextEncoder().encode(encryptionKey); // User-provided key for encryption
// Only check key strength if the algorithm is not 'default'
if (algorithm !== 'default') {
this.checkKeyStrength(encryptionKey); // Validate key strength
}
this.algorithm = algorithm || 'default'; // Default encryption algorithm
this.substitutionKey = {
'a': 'q',
'b': 'w',
'c': 'e',
'd': 'r',
'e': 't',
'f': 'y',
'g': 'u',
'h': 'i',
'i': 'o',
'j': 'p',
'k': 'a',
'l': 's',
'm': 'd',
'n': 'f',
'o': 'g',
'p': 'h',
'q': 'j',
'r': 'k',
's': 'l',
't': 'z',
'u': 'x',
'v': 'c',
'w': 'v',
'x': 'b',
'y': 'n',
'z': 'm',
'A': 'Q',
'B': 'W',
'C': 'E',
'D': 'R',
'E': 'T',
'F': 'Y',
'G': 'U',
'H': 'I',
'I': 'O',
'J': 'P',
'K': 'A',
'L': 'S',
'M': 'D',
'N': 'F',
'O': 'G',
'P': 'H',
'Q': 'J',
'R': 'K',
'S': 'L',
'T': 'Z',
'U': 'X',
'V': 'C',
'W': 'V',
'X': 'B',
'Y': 'N',
'Z': 'M'
};
this.reverseSubstitutionKey = Object.fromEntries(
Object.entries(this.substitutionKey).map(([key, value]) => [value, key])
);
// Affine Cipher Keys
this.a = 5; // Must be coprime to 26
this.b = 8; // Additive key
this.m = 26; // Size of the alphabet
}
// Set the encryption algorithm
setAlgorithm(algorithm) {
this.algorithm = algorithm; // e.g., 'default for tughra', 'caesar', 'vigenere', 'xor'
}
// Check key strength
checkKeyStrength(encryptionKey) {
if (encryptionKey.length < 8) {
throw new Error("Key must be at least 8 characters long.");
}
}
// Main method that either encrypts or decrypts based on the mode
process(text, cycles) {
if (this.useBaseEncoding && this.mode === 'decrypt') {
text = this.fromBase(text); // Convert input from base if required
}
// Check if the algorithm is XOR, ROT47, ROT13 and set cycles to 1 if so
if (this.algorithm === 'xor' || this.algorithm === 'ROT47' || this.algorithm === 'ROT13') {
cycles = 1; // Set cycles to 1 for XOR, ROT47, ROT13
}
let resultText = text;
for (let i = 0; i < cycles; i++) {
resultText = this._processCycle(resultText, this.mode);
}
return this.useBaseEncoding && this.mode === 'encrypt' ? this.toBase(resultText) : resultText;
}
// Process encryption/decryption based on the selected algorithm
_processCycle(text, mode) {
switch (this.algorithm) {
case 'caesar':
return mode === 'encrypt' ? this._caesarEncrypt(text) : this._caesarDecrypt(text);
case 'vigenere':
return mode === 'encrypt' ? this._vigenereEncrypt(text) : this._vigenereDecrypt(text);
case 'xor':
return mode === 'encrypt' ? this._xorEncrypt(text) : this._xorDecrypt(text);
case 'ROT47':
return mode === 'encrypt' ? this._encryptROT47(text) : this._decryptROT47(text);
case 'Atbash':
return mode === 'encrypt' ? this._encryptAtbash(text) : this._decryptAtbash(text);
case 'Substitution':
return mode === 'encrypt' ? this._encryptSubstitution(text) : this._decryptSubstitution(text);
case 'Base64':
return mode === 'encrypt' ? this._encryptBase64(text) : this._decryptBase64(text);
case 'ASCII':
return mode === 'encrypt' ? this._encryptAsciiShift(text) : this._decryptAsciiShift(text);
case 'Affine':
return mode === 'encrypt' ? this._encryptAffine(text) : this._decryptAffine(text);
case 'Unicode Shift':
return mode === 'encrypt' ? this._encryptUnicodeShift(text) : this._decryptUnicodeShift(text);
case 'Numeric':
return mode === 'encrypt' ? this._encryptNumeric(text) : this._decryptNumeric(text);
case 'Reversed Caesar':
return mode === 'encrypt' ? this._encryptReversedCaesar(text) : this._decryptReversedCaesar(text);
case 'ROT13':
return mode === 'encrypt' ? this._encryptROT13(text) : this._decryptROT13(text);
case 'ROT18':
return mode === 'encrypt' ? this._encryptROT18(text) : this._decryptROT18(text);
case 'ROT25':
return mode === 'encrypt' ? this._encryptROT25(text) : this._decryptROT25(text);
case 'ROT30':
return mode === 'encrypt' ? this._encryptROT30(text) : this._decryptROT30(text);
case 'XOR Pro':
return mode === 'encrypt' ? this._encryptXORPro(text, this.keyOffsets) : this._decryptXORPro(text, this.keyOffsets);
case 'Affine Pro':
return mode === 'encrypt' ? this._encryptAffinePro(text, this.encryptionKey) : this._decryptAffinePro(text, this.encryptionKey);
case 'Substitution Pro':
return mode === 'encrypt' ? this._encryptSubstitutionPro(text, this.encryptionKey) : this._decryptSubstitutionPro(text, this.encryptionKey);
default:
return mode === 'encrypt' ? this._TughraEncrypt(text) : this._TughraDecrypt(text);
}
}
_modInverse(a, m) {
for (let x = 1; x < m; x++) {
if ((a * x) % m === 1) {
return x;
}
}
return null; // No modular inverse if not found
}
// 9. Affine Cipher (Encrypt & Decrypt)
_encryptAffine(text) {
return text.split('').map(char => {
if (/[A-Za-z]/.test(char)) { // Check if the character is a letter
const base = char === char.toUpperCase() ? 65 : 97; // Base for uppercase or lowercase
const encryptedChar = String.fromCharCode(((this.a * (char.charCodeAt(0) - base) + this.b) % 26) + base);
return encryptedChar;
}
return char; // Return unchanged if not a letter
}).join('');
}
_decryptAffine(text) {
const a_inv = this._modInverse(this.a, 26);
return text.split('').map(char => {
if (/[A-Za-z]/.test(char)) { // Check if the character is a letter
const base = char === char.toUpperCase() ? 65 : 97; // Base for uppercase or lowercase
const decryptedChar = String.fromCharCode(((a_inv * (char.charCodeAt(0) - base - this.b + 26)) % 26 + 26) % 26 + base);
return decryptedChar;
}
return char; // Return unchanged if not a letter
}).join('');
}
_encryptAffinePro(text) {
return text.split('').map(char => {
if (/[a-zA-Z]/.test(char)) {
const isUpperCase = char === char.toUpperCase();
const base = isUpperCase ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
const x = char.charCodeAt(0) - base; // Convert char to 0-25
const encryptedChar = String.fromCharCode(((this.a * x + this.b) % this.m) + base);
return encryptedChar;
}
return char; // Return unchanged if not a letter
}).join('');
}
_decryptAffinePro(text) {
const aInv = this._modInverse(this.a, this.m);
if (aInv === null) {
throw new Error("No modular inverse exists for the given key 'a'");
}
return text.split('').map(char => {
if (/[a-zA-Z]/.test(char)) {
const isUpperCase = char === char.toUpperCase();
const base = isUpperCase ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
const y = char.charCodeAt(0) - base; // Convert char to 0-25
const decryptedChar = String.fromCharCode((aInv * (y - this.b + this.m)) % this.m + base);
return decryptedChar;
}
return char; // Return unchanged if not a letter
}).join('');
}
_encryptSubstitutionPro(text) {
return text.split('').map(char => {
return this.substitutionKey[char] || char; // Substitute or return unchanged
}).join('');
}
_decryptSubstitutionPro(text) {
return text.split('').map(char => {
return this.reverseSubstitutionKey[char] || char; // Substitute or return unchanged
}).join('');
}
// ROT13 (symmetric)
_encryptROT13(text) {
return text.replace(/[A-Za-z]/g, (char) => {
const base = char <= 'Z' ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
return String.fromCharCode(((char.charCodeAt(0) - base + 13) % 26) + base);
});
}
_decryptROT13(text) {
return this._encryptROT13(text); // ROT13 is symmetric
}
// ROT18 (not symmetric)
_encryptROT18(text) {
return text.replace(/[A-Za-z]/g, (char) => {
const base = char <= 'Z' ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
return String.fromCharCode(((char.charCodeAt(0) - base + 18) % 26) + base);
});
}
_decryptROT18(text) {
return text.replace(/[A-Za-z]/g, (char) => {
const base = char <= 'Z' ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
return String.fromCharCode(((char.charCodeAt(0) - base + 26 - 18) % 26) + base);
});
}
// ROT25 (not symmetric)
_encryptROT25(text) {
return text.replace(/[A-Za-z]/g, (char) => {
const base = char <= 'Z' ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
return String.fromCharCode(((char.charCodeAt(0) - base + 25) % 26) + base);
});
}
_decryptROT25(text) {
return text.replace(/[A-Za-z]/g, (char) => {
const base = char <= 'Z' ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
return String.fromCharCode(((char.charCodeAt(0) - base + 26 - 25) % 26) + base);
});
}
// ROT30 (custom decryption)
_encryptROT30(text) {
return text.replace(/[A-Za-z]/g, (char) => {
const base = char <= 'Z' ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
return String.fromCharCode(((char.charCodeAt(0) - base + 4) % 26) + base);
});
}
_decryptROT30(text) {
return text.replace(/[A-Za-z]/g, (char) => {
const base = char <= 'Z' ? 'A'.charCodeAt(0) : 'a'.charCodeAt(0);
return String.fromCharCode(((char.charCodeAt(0) - base + 22) % 26 + 26) % 26 + base);
});
}
_encryptXORPro(text, key) {
return text.split('').map((char, index) => {
return String.fromCharCode(char.charCodeAt(0) ^ key.charCodeAt(index % key.length));
}).join('');
}
_decryptXORPro(text, key) {
return this._encryptXORPro(text, key); // XOR is symmetric
}
// Default Tughra encryption cycle
_TughraEncrypt(text) {
let encryptedText = '';
for (let i = 0; i < text.length; i++) {
let charCode = text.charCodeAt(i);
// Get the offset by converting the character at keyOffsets[i % keyOffsets.length] to its char code
let offset = this.keyOffsets.charCodeAt(i % this.keyOffsets.length);
encryptedText += String.fromCharCode(charCode + offset);
}
return encryptedText;
}
// Tughra decryption cycle
_TughraDecrypt(encryptedText) {
let decryptedText = '';
for (let i = 0; i < encryptedText.length; i++) {
let charCode = encryptedText.charCodeAt(i);
// Get the offset by converting the character at keyOffsets[i % keyOffsets.length] to its char code
let offset = this.keyOffsets.charCodeAt(i % this.keyOffsets.length);
decryptedText += String.fromCharCode(charCode - offset);
}
return decryptedText;
}
// Caesar Cipher Encryption
_caesarEncrypt(text) {
return text.split('').map(char => String.fromCharCode(char.charCodeAt(0) + this.encryptionKey.length)).join('');
}
_caesarDecrypt(text) {
return text.split('').map(char => String.fromCharCode(char.charCodeAt(0) - this.encryptionKey.length)).join('');
}
// Vigenère Cipher Encryption
_vigenereEncrypt(text) {
const textBytes = new TextEncoder().encode(text); // Convert text to UTF-8 byte array
const encryptedBytes = textBytes.map((byte, i) =>
(byte + this.encryptionKey[i % this.encryptionKey.length]) % 256
);
// Convert encrypted byte array to Base64
return this._arrayBufferToBase64(encryptedBytes);
}
// Vigenère Cipher Decryption
_vigenereDecrypt(encryptedText) {
const encryptedBytes = this._base64ToArrayBuffer(encryptedText); // Decode Base64 to byte array
const decryptedBytes = encryptedBytes.map((byte, i) =>
(byte - this.encryptionKey[i % this.encryptionKey.length] + 256) % 256
);
return new TextDecoder().decode(Uint8Array.from(decryptedBytes)); // Convert decrypted bytes back to text
}
// Helper to convert ArrayBuffer to Base64 safely with chunks
_arrayBufferToBase64(buffer) {
const binary = [];
const bytes = new Uint8Array(buffer);
for (let i = 0; i < bytes.length; i += 8192) {
binary.push(String.fromCharCode(...bytes.slice(i, i + 8192)));
}
return btoa(binary.join(''));
}
// Helper to convert Base64 to ArrayBuffer safely
_base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
// XOR Encryption/Decryption
_xorEncrypt(text) {
if (!this.encryptionKey) throw new Error("Encryption key is missing.");
const textBytes = new TextEncoder().encode(text); // Encode text to UTF-8 byte array
const keyBytes = new TextEncoder().encode(this.encryptionKey);
const encryptedBytes = textBytes.map((byte, i) => byte ^ keyBytes[i % keyBytes.length]);
return btoa(String.fromCharCode(...encryptedBytes)); // Convert to Base64 for safe storage
}
_xorDecrypt(encryptedText) {
const encryptedBytes = atob(encryptedText).split('').map(char => char.charCodeAt(0)); // Decode Base64 and convert to bytes
const keyBytes = new TextEncoder().encode(this.encryptionKey);
const decryptedBytes = encryptedBytes.map((byte, i) => byte ^ keyBytes[i % keyBytes.length]);
return new TextDecoder().decode(Uint8Array.from(decryptedBytes)); // Decode UTF-8 byte array back to text
}
// 1. ROT47 (Encrypt & Decrypt)
_encryptROT47(text) {
return text.replace(/[!-~]/g, char =>
String.fromCharCode(33 + ((char.charCodeAt(0) + 14) % 94))
);
}
_decryptROT47(text) {
return this.encryptROT47(text); // ROT47 is symmetric
}
// 2. Atbash Cipher (Encrypt & Decrypt)
_encryptAtbash(text) {
return text.replace(/[a-zA-Z]/g, char => {
const base = char <= 'Z' ? 65 : 97;
return String.fromCharCode(base + (25 - (char.charCodeAt(0) - base)));
});
}
_decryptAtbash(text) {
return this.encryptAtbash(text); // Atbash is symmetric
}
// 5. Simple Substitution Cipher (Encrypt & Decrypt)
_encryptSubstitution(text) {
return text.split('').map(char =>
this.substitutionKey[char] || char // Leave non-alphabetic characters unchanged
).join('');
}
_decryptSubstitution(text) {
return text.split('').map(char =>
this.reverseSubstitutionKey[char] || char // Leave non-alphabetic characters unchanged
).join('');
}
// 6. Base64 Encoding (Encrypt & Decrypt)
_encryptBase64(text) {
return btoa(text); // Convert to Base64
}
_decryptBase64(base64) {
return atob(base64); // Convert from Base64
}
// 7. ASCII Shift Cipher (Encrypt & Decrypt)
_encryptAsciiShift(text) {
return text.split('').map(char =>
String.fromCharCode(char.charCodeAt(0) + this.encryptionKey.length)
).join('');
}
_decryptAsciiShift(text) {
return text.split('').map(char =>
String.fromCharCode(char.charCodeAt(0) - this.encryptionKey.length)
).join('');
}
// 10. Unicode Shift Cipher (Encrypt & Decrypt)
_encryptUnicodeShift(text) {
return text.split('').map(char =>
String.fromCharCode(char.charCodeAt(0) + this.encryptionKey.length)
).join('');
}
_decryptUnicodeShift(text) {
return text.split('').map(char =>
String.fromCharCode(char.charCodeAt(0) - this.encryptionKey.length)
).join('');
}
// 11. Numeric Cipher (Encrypt & Decrypt)
_encryptNumeric(text) {
return text.split('').map(char =>
char.charCodeAt(0)
).join('-');
}
_decryptNumeric(numbers) {
return numbers.split('-').map(num =>
String.fromCharCode(parseInt(num))
).join('');
}
// 12. Reversed Caesar Cipher (Encrypt & Decrypt)
_encryptReversedCaesar(text) {
return text.replace(/[a-zA-Z]/g, char => {
const base = char <= 'Z' ? 65 : 97;
return String.fromCharCode(((25 - (char.charCodeAt(0) - base) + this.encryptionKey.length) % 26) + base);
});
}
_decryptReversedCaesar(text) {
return text.replace(/[a-zA-Z]/g, char => {
const base = char <= 'Z' ? 65 : 97;
return String.fromCharCode(((25 - (char.charCodeAt(0) - base) - this.encryptionKey.length + 26) % 26) + base);
});
}
// Base encoding function
toBase(text) {
if (!text) return text; // Handle empty text
try {
return this.baseLibrary.encode(unescape(encodeURIComponent(text)));
} catch (error) {
console.error("Base encoding failed:", error);
return text;
}
}
// Base decoding function
fromBase(text) {
if (!text) return text; // Handle empty text
try {
return decodeURIComponent(escape(this.baseLibrary.decode(text)));
} catch (error) {
console.error("Base decoding failed:", error);
return text;
}
}
// Base encoding/decoding library
baseEncodeDecode(alphabet) {
const base = alphabet.length;
const chunkSize = Math.ceil(Math.log(base));
const Library = {
encode: (text) => {
let output = '';
let binary = '';
// Convert text to binary string
for (let i = 0; i < text.length; i++) {
binary += text.charCodeAt(i).toString(2).padStart(8, '0');
}
for (let i = 0; i < binary.length; i += chunkSize) {
const chunk = binary.substring(i, i + chunkSize).padEnd(chunkSize, '0');
const index = parseInt(chunk, 2);
output += alphabet[index]; // Append the corresponding character from the alphabet
}
return output;
},
decode: (text) => {
let binary = '';
// Split based on base
for (let i = 0; i < text.length; i++) {
const index = alphabet.indexOf(text[i]);
if (index === -1) throw new Error('Invalid Base character');
binary += index.toString(2).padStart(chunkSize, '0'); // Convert to binary based on chunk size
}
// Convert binary string to text
let output = '';
for (let i = 0; i < binary.length; i += 8) {
const chunk = binary.substring(i, i + 8);
if (chunk.length === 8) {
output += String.fromCharCode(parseInt(chunk, 2));
}
}
return output;
}
};
return Library;
}
}
class TughraLibrary {
constructor() {
// Define Unicode groups for character generation
this.unicodeGroups = [{
name: 'Numbers',
start: 48,
end: 57
}, // 0-9
{
name: 'Lowercase English',
start: 97,
end: 122
}, // a-z
{
name: 'Uppercase English',
start: 65,
end: 90
}, // A-Z
{
name: 'Basic Latin',
start: 33,
end: 127
},
{
name: 'Latin-1 Supplement',
start: 128,
end: 255
},
{
name: 'Latin Extended-A',
start: 256,
end: 383
},
{
name: 'Latin Extended-B',
start: 384,
end: 591
},
{
name: 'IPA Extensions',
start: 592,
end: 687
},
{
name: 'Greek and Coptic',
start: 880,
end: 1023
},
{
name: 'Cyrillic',
start: 1024,
end: 1279
},
{
name: 'Arabic',
start: 1536,
end: 1791
},
{
name: 'Hebrew',
start: 1424,
end: 1535
},
{
name: 'Devanagari',
start: 2304,
end: 2431
},
{
name: 'Bengali',
start: 2432,
end: 2559
},
{
name: 'Gurmukhi',
start: 2560,
end: 2687
},
{
name: 'Gujarati',
start: 2688,
end: 2815
},
{
name: 'Oriya',
start: 2816,
end: 2943
},
{
name: 'Tamil',
start: 2944,
end: 3071
},
{
name: 'Telugu',
start: 3072,
end: 3199
},
{
name: 'Kannada',
start: 3200,
end: 3327
},
{
name: 'Malayalam',
start: 3328,
end: 3455
},
{
name: 'Thai',
start: 3584,
end: 3711
},
{
name: 'Lao',
start: 3712,
end: 3839
},
{
name: 'Tibetan',
start: 3840,
end: 4095
},
{
name: 'Georgian',
start: 4256,
end: 4351
},
{
name: 'Hangul Jamo',
start: 4352,
end: 4607
},
{
name: 'Latin Extended Additional',
start: 7680,
end: 7935
},
{
name: 'Greek Extended',
start: 7936,
end: 8191
},
{
name: 'General Punctuation',
start: 8192,
end: 8303
},
{
name: 'Superscripts and Subscripts',
start: 8304,
end: 8351
},
{
name: 'Currency Symbols',
start: 8352,
end: 8399
},
{
name: 'Combining Diacritical Marks',
start: 8400,
end: 8447
},
{
name: 'Letterlike Symbols',
start: 8448,
end: 8527
},
{
name: 'Number Forms',
start: 8528,
end: 8591
},
{
name: 'Arrows',
start: 8592,
end: 8703
},
{
name: 'Mathematical Operators',
start: 8704,
end: 8959
},
{
name: 'Miscellaneous Technical',
start: 8960,
end: 9215
},
{
name: 'Control Pictures',
start: 9216,
end: 9279
},
{
name: 'Optical Character Recognition',
start: 9280,
end: 9311
},
{
name: 'Enclosed Alphanumerics',
start: 9312,
end: 9471
},
{
name: 'Box Drawing',
start: 9472,
end: 9599
},
{
name: 'Block Elements',
start: 9600,
end: 9631
},
{
name: 'Geometric Shapes',
start: 9632,
end: 9727
},
{
name: 'Miscellaneous Symbols',
start: 9728,
end: 9983
},
{
name: 'Dingbats',
start: 9984,
end: 10175
},
{
name: 'Braille Patterns',
start: 10240,
end: 10495
},
{
name: 'CJK Symbols and Punctuation',
start: 12288,
end: 12351
},
{
name: 'Hiragana',
start: 12352,
end: 12447
},
{
name: 'Katakana',
start: 12448,
end: 12543
},
{
name: 'Bopomofo',
start: 12544,
end: 12591
},
{
name: 'Hangul Compatibility Jamo',
start: 12592,
end: 12687
},
{
name: 'Phonetic Extensions',
start: 12704,
end: 12735
},
{
name: 'Enclosed CJK Letters and Months',
start: 12800,
end: 13055
},
{
name: 'CJK Compatibility',
start: 13056,
end: 13311
},
{
name: 'CJK Unified Ideographs',
start: 19968,
end: 40959
},
{
name: 'Hangul Syllables',
start: 44032,
end: 55215
},
{
name: 'Private Use Area',
start: 57344,
end: 63743
},
{
name: 'CJK Compatibility Ideographs',
start: 63744,
end: 64255
},
{
name: 'Alphabetic Presentation Forms',
start: 64256,
end: 64335
},
{
name: 'Arabic Presentation Forms-A',
start: 64336,
end: 65023
},
{
name: 'Variation Selectors',
start: 65024,
end: 65039
},
{
name: 'Combining Half Marks',
start: 65056,
end: 65071
},
{
name: 'CJK Compatibility Forms',
start: 65072,
end: 65103
},
{
name: 'Small Form Variants',