-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path_3_Rail_Fence.java
104 lines (82 loc) · 2.73 KB
/
_3_Rail_Fence.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
package com.company.ISC;
import java.util.Scanner;
public class _3_Rail_Fence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the plain text : ");
String pt = sc.nextLine();
System.out.print("Enter the key : ");
int key = sc.nextInt();
String en = encryption(pt, key);
System.out.println("Encrypted text is : " + en);
String dn = decryption(en, key);
System.out.println("Decrypted text is : " + dn);
}
private static String encryption(String plain, int key) {
String encryptedText = "";
int col = plain.length();
int row = key;
boolean check = false;
int j = 0;
char[][] rail = new char[row][col];
//to fill the array:
for (int i = 0; i < row; i++) {
for (int k = 0; k < col; k++) rail[i][k] = '*';
}
for (int i = 0; i < col; i++) {
if (j == 0 || j == key - 1) check = !check;
rail[j][i] = plain.charAt(i);
if (check) j++;
else j--;
}
System.out.println("Rail of encryption : ");
for (int i = 0; i < row; i++) {
for (int k = 0; k < col; k++) {
char ch = rail[i][k];
if (ch != '*') encryptedText += rail[i][k];
System.out.print(ch + " ");
}
System.out.println();
}
return encryptedText;
}
private static String decryption(String encrypted, int key) {
String decryptedText = "";
int col = encrypted.length();
int row = key;
boolean check = false;
int j = 0;
char[][] rail = new char[row][col];
//to fill the array:
for (int i = 0; i < row; i++) {
for (int k = 0; k < col; k++) rail[i][k] = '*';
}
for (int i = 0; i < col; i++) {
if (j == 0 || j == key - 1) check = !check;
rail[j][i] = '#';
if (check) j++;
else j--;
}
System.out.println("Rails for decryption : ");
int index = 0;
for (int i = 0; i < row; i++) {
for (int k = 0; k < col; k++) {
char ch = rail[i][k];
if (ch == '#' && index < col) {
rail[i][k] = encrypted.charAt(index++);
}
System.out.print(ch + " ");
}
System.out.println();
}
j = 0;
check = false;
for (int i = 0; i < col; i++) {
if (j == 0 || j == key - 1) check = !check;
decryptedText += rail[j][i];
if (check) j++;
else j--;
}
return decryptedText;
}
}