1// Aim: Program to perform Rail fence cipher (Rail fence Cipher).
2public class railfence {
3 public static String encrypt(String text, int key) {
4 if (key <= 1) return text;
5 StringBuilder[] rail = new StringBuilder[key];
6 for (int i = 0; i < key; i++) rail[i] = new StringBuilder();
7
8 int dir = 1, row = 0;
9 for (char c : text.toCharArray()) {
10 rail[row].append(c);
11 row += dir;
12 if (row == 0 || row == key - 1) dir *= -1;
13 }
14
15 StringBuilder result = new StringBuilder();
16 for (StringBuilder sb : rail) result.append(sb);
17 return result.toString();
18 }
19
20 public static String decrypt(String cipher, int key) {
21 if (key <= 1) return cipher;
22 int len = cipher.length();
23 boolean[][] mark = new boolean[key][len];
24
25 int dir = 1, row = 0;
26 for (int i = 0; i < len; i++) {
27 mark[row][i] = true;
28 row += dir;
29 if (row == 0 || row == key - 1) dir *= -1;
30 }
31
32 char[] result = new char[len];
33 int idx = 0;
34 for (int i = 0; i < key; i++) {
35 for (int j = 0; j < len; j++) {
36 if (mark[i][j] && idx < len) {
37 result[j] = cipher.charAt(idx++);
38 }
39 }
40 }
41
42 StringBuilder plain = new StringBuilder();
43 row = 0; dir = 1;
44 for (int i = 0; i < len; i++) {
45 plain.append(result[i]);
46 row += dir;
47 if (row == 0 || row == key - 1) dir *= -1;
48 }
49 return plain.toString();
50 }
51
52 public static void main(String[] args) {
53 String text = "WEAREDISCOVEREDFLEEATONCE";
54 int key = 3;
55 String encrypted = encrypt(text, key);
56 System.out.println("Encrypted: " + encrypted);
57 String decrypted = decrypt(encrypted, key);
58 System.out.println("Decrypted: " + decrypted);
59 }
60}
61