forked from ravipatel447/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrail_fence.java
94 lines (88 loc) · 2.82 KB
/
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
import java.util.Scanner;
public class rail_fence {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Message:");
String s = sc.nextLine();
System.out.println("Enter a key");
int key = sc.nextInt();
// String encrypted = encrypt(s, key);
String decrypted = decryptRailFence(s, key);
// System.out.println("Encrypted message: "+encrypted);
System.out.println("Decrypted message: "+decrypted);
System.out.println("19DCE111:- Ravi Patel");
}
public static String encrypt(String plaintext, int key) {
char[][] ar = new char[key][plaintext.length()];
boolean dir_down = false;
int row = 0, col = 0;
for (int i = 0; i < key; i++) {
for (int j = 0; j < plaintext.length(); j++) {
ar[i][j] = '~';
}
}
for (int i = 0; i < plaintext.length(); i++) {
if (row == 0 || row == key - 1)
dir_down = !dir_down;
ar[row][col++] = plaintext.charAt(i);
if (dir_down) {
row++;
} else {
row--;
}
}
String ciphertext = "";
for (int i = 0; i < key; i++) {
for (int j = 0; j < plaintext.length(); j++) {
if (ar[i][j] != '~')
ciphertext += ar[i][j];
}
}
return ciphertext;
}
public static String decryptRailFence(String cipher, int key) {
char[][] ar = new char[key][cipher.length()];
for (int i = 0; i < key; i++) {
for (int j = 0; j < cipher.length(); j++) {
ar[i][j] = '~';
}
}
boolean dir_down = true;
int row = 0, col = 0;
for (int i = 0; i < cipher.length(); i++) {
if (row == 0)
dir_down = true;
if (row == key - 1)
dir_down = false;
ar[row][col++] = '*';
if (dir_down) {
row++;
} else {
row--;
}
}
int index = 0;
for (int i = 0; i < key; i++)
for (int j = 0; j < cipher.length(); j++)
if (ar[i][j] == '*' && index < cipher.length())
ar[i][j] = cipher.charAt(index++);
String result = "";
row = 0;
col = 0;
for (int i = 0; i < cipher.length(); i++) {
if (row == 0)
dir_down = true;
if (row == key - 1)
dir_down = false;
if (ar[row][col] != '*') {
result += ar[row][col++];
}
if (dir_down) {
row++;
} else {
row--;
}
}
return result;
}
}