-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaesarCracker.java
54 lines (45 loc) · 1.32 KB
/
CaesarCracker.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
import edu.duke.*;
public class CaesarCracker {
char mostCommon;
public CaesarCracker() {
mostCommon = 'e';
}
public CaesarCracker(char c) {
mostCommon = c;
}
public int[] countLetters(String message){
String alph = "abcdefghijklmnopqrstuvwxyz";
int[] counts = new int[26];
for(int k=0; k < message.length(); k++){
int dex = alph.indexOf(Character.toLowerCase(message.charAt(k)));
if (dex != -1){
counts[dex] += 1;
}
}
return counts;
}
public int maxIndex(int[] vals){
int maxDex = 0;
for(int k=0; k < vals.length; k++){
if (vals[k] > vals[maxDex]){
maxDex = k;
}
}
return maxDex;
}
public int getKey(String encrypted){
int[] freqs = countLetters(encrypted);
int maxDex = maxIndex(freqs);
int mostCommonPos = mostCommon - 'a';
int dkey = maxDex - mostCommonPos;
if (maxDex < mostCommonPos) {
dkey = 26 - (mostCommonPos-maxDex);
}
return dkey;
}
public String decrypt(String encrypted){
int key = getKey(encrypted);
CaesarCipher cc = new CaesarCipher(key);
return cc.decrypt(encrypted);
}
}