-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRailFenceCipherDecryption.java
68 lines (68 loc) · 2.64 KB
/
RailFenceCipherDecryption.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
import java.util.Scanner;
public class RailFenceCipherDecryption {
// Function to decrypt the Rail Fence Cipher
public static String decrypt(String encryptedMessage, int rails) {
// Create a 2D array to represent the rail fence
char[][] railFence = new char[rails][encryptedMessage.length()];
// Initialize the rail fence with dots
for (int i = 0; i < rails; i++) {
for (int j = 0; j < encryptedMessage.length(); j++) {
railFence[i][j] = '.';
}
}
// Fill in the characters in a zigzag pattern
int row = 0;
boolean down = true;
for (int i = 0; i < encryptedMessage.length(); i++) {
railFence[row][i] = 'X'; // Mark the position of the characters
if (row == 0) {
down = true;
} else if (row == rails - 1) {
down = false;
}
if (down) {
row++;
} else {
row--;
}
}
// Read the characters in the zigzag pattern to recover the original message
int index = 0;
for (int i = 0; i < rails; i++) {
for (int j = 0; j < encryptedMessage.length(); j++) {
if (railFence[i][j] == 'X') {
railFence[i][j] = encryptedMessage.charAt(index++);
}
}
}
// Read the characters row by row to get the decrypted message
StringBuilder decryptedMessage = new StringBuilder();
row = 0;
down = true;
for (int i = 0; i < encryptedMessage.length(); i++) {
decryptedMessage.append(railFence[row][i]);
if (row == 0) {
down = true;
} else if (row == rails - 1) {
down = false;
}
if (down) {
row++;
} else {
row--;
}
}
return decryptedMessage.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the encrypted message: ");
String encryptedMessage = scanner.nextLine();
System.out.print("Enter the number of rails: ");
int rails = scanner.nextInt();
// Decrypt the message
String decryptedMessage = decrypt(encryptedMessage, rails);
// Display the decrypted message
System.out.println("Decrypted message: " + decryptedMessage);
}
}