Tiny tool to do monoalphabetic substitution
1function get_key() {
2 var map = [];
3 for (let i = 0; i < 26; i++) {
4 map.push($("#" +String.fromCharCode(i + 65)).val());
5 }
6
7 for (let i = 0; i < map.length; i++) {
8 if (!(typeof map[i] === 'string' || map[i] instanceof String) || map[i].length < 1) {
9 map[i] = String.fromCharCode(i + 65);
10 } else {
11 const code = map[i].charCodeAt(0);
12 if (map[i].length > 1) {
13 map[i] = map[i][0];
14 $("#" +String.fromCharCode(i + 65)).val(map[i][0]);
15 } else if (code >= 65 && code <= 90) {
16 map[i] = String.fromCharCode(code + 32);
17 }
18 }
19 }
20
21 return map;
22}
23
24function encrypt(plaintext, key) {
25 var encrypted = "";
26
27 var text = plaintext.toUpperCase();
28 for (let i = 0; i < text.length; i++) {
29 const code = text.charCodeAt(i);
30 if (code >= 65 && code <= 90) {
31 encrypted += key[code - 65];
32 } else {
33 encrypted += text[i];
34 }
35 }
36
37 return encrypted;
38}
39
40function decrypt(encrypted, key) {
41 var plaintext = "";
42
43 var text = encrypted.toLowerCase()
44 for (let i = 0; i < text.length; i++) {
45 var loc = key.indexOf(text[i]);
46 const code = text.charCodeAt(i);
47 if (loc >= 0) {
48 plaintext += String.fromCharCode(loc + 97);
49 } else if (97 <= code && code <= 122) {
50 plaintext += String.fromCharCode(code - 32);
51 } else {
52 plaintext += text[i];
53 }
54 }
55
56 return plaintext;
57}
58
59$(document).ready(function() {
60 $("#encrypt").button().click(function(){
61 var key = get_key();
62 var text = $("#plain-text").val();
63 $("plain-text").val(text.toLowerCase());
64 var encrypted = encrypt(text, key);
65 $("#encrypted-text").val(encrypted);
66 });
67 $("#decrypt").button().click(function(){
68 var key = get_key();
69 var text = $("#encrypted-text").val();
70 $("#encrypted-text").val(text.toLowerCase());
71 var decrypted = decrypt(text, key);
72 $("#plain-text").val(decrypted);
73 });
74 $("#generate-alpha").button().click(function(){
75 var key = get_key();
76 var alpha = "";
77 for (let i = 0; i < key.length; i++) {
78 alpha += key[i];
79 }
80 $("#alphabet").val(alpha);
81 });
82 $("#import-alpha").button().click(function(){
83 var alpha = $("#alphabet").val();
84 if (alpha.length != 26) {
85 alert("Alphabet of invalid length");
86 return;
87 }
88 alpha = alpha.toUpperCase();
89 for (let i = 0; i < alpha.length; i++) {
90 const code = alpha.charCodeAt(i);
91 if (code != i + 65) {
92 $("#" +String.fromCharCode(i + 65)).val(alpha[i]);
93 }
94 }
95 });
96});