-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncrypt.java
91 lines (81 loc) · 2.49 KB
/
Encrypt.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
//Karolien Koorts
import java.util.*;
import java.util.concurrent.*;
import javax.swing.*;
public class Encrypt extends SwingWorker<Void, String> {
String key, message;
JTextArea result;
int keyLength, messageLength;
boolean encrypt;
public Encrypt(JTextArea result, String key, String message, boolean encrypt) {
this.result = result;
this.key = key.toUpperCase();
this.message = message.toUpperCase();
this.keyLength = key.length();
this.messageLength = message.length();
this.encrypt = encrypt;
}
@Override
public Void doInBackground() throws Exception {
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
char[] alphabetChar = alphabet.toCharArray();
//Set up alphabet HashMap
HashMap<Character, Integer> hm1 = new HashMap<Character, Integer>();
for (int i=0; i<26; i++){
hm1.put(alphabet.charAt(i), i);
}
//Set up Vigenère table HashMap
HashMap<Character, String> hm2 = new HashMap<Character, String>();
for (int k=0; k<26; k++){
String derangedAlpha = alphabet.substring(k);
derangedAlpha += alphabet.substring(0, k);
String value = derangedAlpha;
hm2.put(alphabet.charAt(k), value);
}
Character currentChar;
int keyCount = 0;
if (encrypt){
//Encrypt message
for (int x=0; x<messageLength; x++){
currentChar = message.charAt(x);
if (!Character.isLetter(currentChar)){
result.append(currentChar.toString());
}
else{
Integer letterValue = hm1.get(currentChar);
String alphaUsed = hm2.get(key.charAt(keyCount));
Character encryptedLetter = alphaUsed.charAt(letterValue);
result.append(encryptedLetter.toString());
if(keyCount==keyLength-1){
keyCount = 0;
}
else{
keyCount++;
}
}
}
}
else{
//Decrypt message
for (int y=0; y<messageLength;y++){
currentChar = message.charAt(y);
if (!Character.isLetter(currentChar)){
result.append(currentChar.toString());
}
else{
String decodeAlpha = hm2.get(key.charAt(keyCount));
Integer letterPos = decodeAlpha.indexOf(currentChar);
Character finalLetter = alphabetChar[letterPos];
result.append(finalLetter.toString());
if(keyCount==keyLength-1){
keyCount = 0;
}
else{
keyCount++;
}
}
}
}
return null;
}
}