forked from scr34m0/Java-Cryptools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRailfenceCipher.java
More file actions
103 lines (100 loc) · 2.4 KB
/
RailfenceCipher.java
File metadata and controls
103 lines (100 loc) · 2.4 KB
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
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* @author arthur.paixao
* @category Rail Fence Cipher Encode/Decode
*/
public class RailfenceCipher {
public void encrypt(String line, int rail) {
System.out.println("Result:");
int shift = 0, p = 0, itr;
for (int i = 0; i < rail; i++) {
p = i;
if (i == 0 || i == rail - 1)
shift = ((rail - 2) * 2) + 2;
itr = 1;
while (p < line.length()) {
System.out.print(line.charAt(p));
if (i != 0 && i != rail - 1) {
shift = ((rail * itr - itr) - p) * 2;
}
p += shift;
itr++;
}
}
}
public void decrypt(String line, int arr[]) {
System.out.println("Result:");
int ptr[] = new int[arr.length + 1];
int p1 = 0, p2 = 0, p3 = 0, c = 1;
boolean chk = true;
System.out.print(line.charAt(ptr[p3] + p1));
ptr[p3]++;
while (c < line.length()) {
if (chk) {
p1 += arr[p2];
p2++;
p3++;
} else {
p1 -= arr[p2];
p2--;
p3--;
}
System.out.print(line.charAt(ptr[p3] + p1));
c++;
ptr[p3]++;
if (p2 == arr.length) {
p2--;
chk = false;
} else if (p2 == -1) {
p2++;
chk = true;
}
}
}
public static void main(String args[]) throws IOException {
RailfenceCipher obj = new RailfenceCipher();
String line;
int rail, arr[], temp;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("MENU:\n1) Encryption:\n2) Decryption:");
int choice = Integer.parseInt(in.readLine());
System.out.println("Enter the string:");
line = in.readLine();
System.out.println("Enter the no of rails:");
rail = Integer.parseInt(in.readLine());
switch (choice) {
case 1:
temp = line.length() - rail;
int spaces;
if (temp % (rail - 1) != 0) {
spaces = (rail - 1) - (temp % (rail - 1));
if ((temp / (rail - 1)) % 2 != 0) {
spaces += rail - 1;
}
} else {
spaces = temp % (rail - 1);
if ((temp / (rail - 1)) % 2 == 0) {
spaces += rail - 1;
}
}
for (int g = 0; g < spaces; g++)
line += ' ';
obj.encrypt(line, rail);
break;
case 2:
temp = line.length() - rail;
arr = new int[rail - 1];
if ((temp / (rail - 1)) % 2 == 0)
arr[0] = 1 + (temp / (rail - 1)) / 2;
else
arr[0] = 1 + ((temp / (rail - 1)) + 1) / 2;
arr[1] = arr[0] * 2 - 2;
for (int i = 2; i < rail - 1; i++)
arr[i] = arr[1];
obj.decrypt(line, arr);
break;
}
}
}