-
Notifications
You must be signed in to change notification settings - Fork 30
/
RailFence.java
107 lines (97 loc) · 2.13 KB
/
RailFence.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package cryptography.ciphers.railfence;
import cryptography.Mode;
public class RailFence {
public static void main(String[] args) {
}
/**
* Rail Fence cipher
*
* @param input inputText Text to cipher / decipher
* @param mode encrypt or decrypt mode
* @param key Number value
* @return String based on selected mode
*/
public static String railFence(String input, Mode mode, int key) {
input = input.toLowerCase();
String output = "";
final char NULLCHAR = '\u0000';
int rails = key;
char[][] fence;
if (mode == Mode.ENCRYPT) {
fence = new char[rails][input.length()];
char[] m = input.toCharArray();
int row = 0;
boolean down = true;
for (int col = 0; col < input.length(); col++) {
fence[row][col] = m[col];
if (down) {
if (row < rails - 1) {
row++;
} else {
down = false;
row--;
}
} else {
if (row > 0) {
row--;
} else {
down = true;
row++;
}
}
}
for (int i = 0; i < rails; i++) {
for (int j = 0; j < fence[i].length; j++) {
if (fence[i][j] != NULLCHAR)
output += fence[i][j];
}
}
}
if (mode == Mode.DECRYPT) {
String placeholder = "";
char phChar = 'X';
for (int i = 0; i < input.length(); i++) {
placeholder += phChar;
}
fence = new char[rails][input.length()];
char[] m = placeholder.toCharArray();
int row = 0;
boolean down = true;
for (int col = 0; col < input.length(); col++) {
fence[row][col] = m[col];
if (down) {
if (row < rails - 1) {
row++;
} else {
down = false;
row--;
}
} else {
if (row > 0) {
row--;
} else {
down = true;
row++;
}
}
}
char[] n = input.toCharArray();
int index = 0;
for (int i = 0; i < rails; i++) {
for (int j = 0; j < input.length(); j++) {
if (fence[i][j] == phChar) {
fence[i][j] = n[index];
index++;
}
}
}
for (int j = 0; j < fence[0].length; j++) {
for (int i = 0; i < rails; i++) {
if (fence[i][j] != NULLCHAR)
output += fence[i][j];
}
}
}
return output.replace("\u0000", "");
}
}