Skip to content

Commit bbc6927

Browse files
authored
Create MonoAlphabetic.java
1 parent 6f5b5fc commit bbc6927

File tree

1 file changed

+79
-0
lines changed

1 file changed

+79
-0
lines changed
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
package MonoAlphabetic_Cipher;
2+
import java.util.Scanner;
3+
4+
public class MonoAlphabetic {
5+
public static void main(String[] args) {
6+
Scanner read = new Scanner(System.in);
7+
System.out.println("Hello User! \nEnter your name:");
8+
String name = read.nextLine();
9+
read.nextLine();
10+
11+
System.out.println("Welcome "+name+"!\nDo you want to encrypt data or decrypt the data?\nFor encryption enter: 1\nFor decryption enter: 2");
12+
int x = read.nextInt();
13+
read.nextLine();
14+
15+
String key = "MNBVCXZLKJHGFDSAPOIUYTREWQ";
16+
17+
switch (x) {
18+
case 1:
19+
System.out.println("\nPlease enter the data that is to be encrypted, we will be using MonoAlphabetic Cipher to encrypt the data.");
20+
String data = read.nextLine().toUpperCase();;
21+
22+
String encryptedData = encrypt(data,key);
23+
System.out.println("Encrypted data: " + encryptedData);
24+
break;
25+
26+
case 2:
27+
System.out.println("\nPlease enter the data that is to be decrypted, we will be using MonoAlphabetic Cipher to decrypt the data.");
28+
data = read.nextLine().toUpperCase();;
29+
30+
String decryptedData = decrypt(data,key);
31+
System.out.println("Decrypted data: " + decryptedData);
32+
break;
33+
34+
default:
35+
System.out.println("The input was invalid. Kindly restart.");
36+
break;
37+
}
38+
39+
40+
}
41+
42+
public static String encrypt(String data, String key){
43+
int idx;
44+
char c;
45+
StringBuffer sb = new StringBuffer(data);
46+
47+
for(int i=0; i<sb.length(); i++){
48+
idx = sb.charAt(i)-65;
49+
c = key.charAt(idx);
50+
sb.setCharAt(i, c);
51+
}
52+
return new String(sb);
53+
}
54+
55+
public static String decrypt(String data, String key){
56+
int idx;
57+
char c;
58+
StringBuffer sb = new StringBuffer(data);
59+
60+
for(int i=0; i<sb.length(); i++){
61+
c = sb.charAt(i);
62+
idx = getIndex(c,key);
63+
c = (char) (idx + 65);
64+
sb.setCharAt(i, c);
65+
}
66+
return new String(sb);
67+
}
68+
69+
public static int getIndex(char c, String key){
70+
int idx = -1;
71+
for(int i=0; i<key.length();i++){
72+
if(key.charAt(i) == c){
73+
idx = i;
74+
}
75+
}
76+
return idx;
77+
}
78+
79+
}

0 commit comments

Comments
 (0)