-
Notifications
You must be signed in to change notification settings - Fork 30
/
Atbash.java
64 lines (53 loc) · 1.59 KB
/
Atbash.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
package cryptography.ciphers.atbash;
import cryptography.Mode;
public class Atbash {
private static final String PLAIN = "abcdefghijklmnopqrstuvwxyz";
private static final String CIPHER = "zyxwvutsrqponmlkjihgfedcba";
public static void main(String[] args) {
}
/**
* Atbash cipher
*
* @param inputText Text to cipher / decipher
* @param mode encrypt or decrypt mode
* @return String based on selected mode
*/
public static String atbash(String inputText, final Mode mode) {
try {
inputText = inputText.toLowerCase();
String output = null;
if (mode == Mode.ENCRYPT) {
String encoded = stripInvalidCharacters(inputText).toLowerCase();
StringBuilder cyphered = new StringBuilder();
for (char c : encoded.toCharArray()) {
cyphered.append(applyCipher(c));
}
output = cyphered.toString();
}
if (mode == Mode.DECRYPT) {
String encoded = stripInvalidCharacters(inputText).toLowerCase();
StringBuilder deciphered = new StringBuilder();
for (char c : encoded.toCharArray()) {
deciphered.append(applyCipher(c));
}
output = deciphered.toString();
}
return output;
} catch (Exception e) {
return e.toString();
}
}
private static String stripInvalidCharacters(String input) {
StringBuilder filteredValue = new StringBuilder();
for (char c : input.toCharArray()) {
if (Character.isLetterOrDigit(c)) {
filteredValue.append(c);
}
}
return filteredValue.toString();
}
private static char applyCipher(char input) {
int idx = PLAIN.indexOf(input);
return idx >= 0 ? CIPHER.toCharArray()[idx] : input;
}
}