-
Notifications
You must be signed in to change notification settings - Fork 0
/
EncryptionProgram.java
126 lines (108 loc) · 3.41 KB
/
EncryptionProgram.java
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
import java.util.*;
public class EncryptionProgram {
private Scanner scanner;
private Random random;
private ArrayList<Character> list;
private ArrayList<Character> shuffledList;
private char character;
private String line;
private char[] letters;
private char[] secreteLetters;
EncryptionProgram(){
scanner = new Scanner(System.in);
random = new Random();
list = new ArrayList<>();
shuffledList = new ArrayList<>();
character = ' ';
newKey();
askQuestion();
}
private void askQuestion(){
while(true){
System.out.println("*******************************************************");
System.out.println("What do you want to do? ");
System.out.println("(N)ewKey, (G)etKey, (E)ncrypt, (D)ecrypt, (Q)uit");
char response = Character.toUpperCase(scanner.nextLine().charAt(0));
switch(response){
case 'N':
newKey();
break;
case 'G':
getKey();
break;
case 'E':
encrypt();
break;
case 'D':
decrypt(secreteLetters);
break;
case 'Q':
quit();
break;
default:
System.out.println("Invalid choice ");
}
}
}
private void newKey(){
character = ' ';
list.clear();
shuffledList.clear();
for(int i = 32; i<127; i++ ){
list.add(Character.valueOf(character));
character++;
}
shuffledList = new ArrayList<>(list);
Collections.shuffle(shuffledList);
System.out.println("A new key has been created");
}
private void getKey(){
System.out.println("Key: ");
for(Character x : list){
System.out.print(x);
}
System.out.println();
for(Character x : shuffledList){
System.out.print(x);
}
System.out.println();
}
private void encrypt(){
System.out.println("Enter a message to be encrypted: ");
String message = scanner.nextLine();
letters = message.toCharArray();
for(int i = 0; i<letters.length; i++){
for(int j = 0; j<list.size(); j++){
if(letters[i]==list.get(j)){
letters[i]=shuffledList.get(j);
break;
}
}
}
System.out.println("Encrypted message: ");
for(char x : letters){
System.out.print(x);
}
secreteLetters = letters;
System.out.println();
}
private void decrypt(char[] secreteLetters){
for(int i = 0; i<secreteLetters.length; i++){
for(int j = 0; j<shuffledList.size(); j++){
if(secreteLetters[i]==shuffledList.get(j)){
secreteLetters[i]=list.get(j);
break;
}
}
}
System.out.println("Decrypted message: ");
for(char x : secreteLetters){
System.out.print(x);
}
System.out.println();
}
private void quit(){
System.out.println("Thank you, have a nice day bro. Bye!");
System.exit(0);
}
}