-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathScytale.java
63 lines (55 loc) · 1.49 KB
/
Scytale.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
package cryptography.ciphers.scytale;
import cryptography.Mode;
public class Scytale {
public static void main(String[] args) {
}
/**
* Scytale cipher
*
* @see <a href="https://en.wikipedia.org/wiki/Scytale</a>
* @param input Text to cipher / decipher
* @param mode encrypt or decrypt mode
* @param diameter Baton/cylinder diameter
* @return String based on selected mode
*/
public static String scytale(String input, Mode mode, int diameter) {
String output = "";
final char NULLCHAR = '\u0000';
char[][] rod;
int width = diameter;
int height = input.length() % width == 0 ? input.length() / width : input.length() / width + 1;
if (mode == Mode.ENCRYPT) {
rod = new char[height][width];
int index = 0;
char[] text = input.toCharArray();
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
rod[i][j] = index < text.length ? text[index] : NULLCHAR;
index++;
}
}
for (int j = 0; j < width; j++) {
for (int i = 0; i < height; i++) {
output += rod[i][j];
}
}
}
if (mode == Mode.DECRYPT) {
rod = new char[height][width];
int index = 0;
char[] text = input.toCharArray();
for (int j = 0; j < width; j++) {
for (int i = 0; i < height; i++) {
rod[i][j] = index < input.length() ? text[index] : NULLCHAR;
index++;
}
}
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
output += rod[i][j];
}
}
}
return output.replace("\u0000", "");
}
}