-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCaesarCipher.java
55 lines (45 loc) · 1.52 KB
/
CaesarCipher.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
import edu.duke.*;
public class CaesarCipher {
private String alphabet;
private String shiftedAlphabet;
private int theKey;
public CaesarCipher(int key) {
theKey = key;
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
shiftedAlphabet = alphabet.substring(key) +
alphabet.substring(0,key);
alphabet = alphabet + alphabet.toLowerCase();
shiftedAlphabet = shiftedAlphabet + shiftedAlphabet.toLowerCase();
}
private char transformLetter(char c, String from, String to) {
int idx = from.indexOf(c);
if (idx != -1) {
return to.charAt(idx);
}
return c;
}
public char encryptLetter(char c) {
return transformLetter(c, alphabet, shiftedAlphabet);
}
public char decryptLetter(char c) {
return transformLetter(c, shiftedAlphabet, alphabet);
}
private String transform(String input, String from, String to){
StringBuilder sb = new StringBuilder(input);
for (int i = 0; i < sb.length(); i++) {
char c = sb.charAt(i);
c = transformLetter(c, from, to);
sb.setCharAt(i, c);
}
return sb.toString();
}
public String encrypt(String input) {
return transform(input, alphabet, shiftedAlphabet);
}
public String decrypt(String input) {
return transform(input, shiftedAlphabet, alphabet);
}
public String toString() {
return "" + theKey;
}
}