forked from FirmanKurniawan/Java-Projects
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRailFence.java
More file actions
87 lines (79 loc) · 2.38 KB
/
RailFence.java
File metadata and controls
87 lines (79 loc) · 2.38 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
import java.util.Scanner;
/*
* Rail fence cipher
* The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher.
* It derives its name from the way in which it is encoded.
*
* Code by @hexaorzo
*/
class RailFenceBasic {
int depth;
String Encryption(String plainText, int depth) throws Exception {
int r = depth, len = plainText.length();
int c = len / depth;
char mat[][] = new char[r][c];
int k = 0;
String cipherText = "";
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
if (k != len)
mat[j][i] = plainText.charAt(k++);
else
mat[j][i] = 'X';
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
cipherText += mat[i][j];
}
}
return cipherText;
}
String Decryption(String cipherText, int depth) throws Exception {
int r = depth, len = cipherText.length();
int c = len / depth;
char mat[][] = new char[r][c];
int k = 0;
String plainText = "";
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
mat[i][j] = cipherText.charAt(k++);
}
}
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
plainText += mat[j][i];
}
}
return plainText;
}
}
class RailFence {
public static void main(String args[]) throws Exception {
RailFenceBasic rf = new RailFenceBasic();
Scanner input = new Scanner(System.in);
int depth = 0;
System.out.println("Please enter the message (Latin Alphabet)");
String message = input.nextLine();
System.out.println(message);
System.out.println("(E)ncode or (D)ecode");
char choice = input.next().charAt(0);
switch (choice) {
case 'E':
case 'e':
System.out.println("Please enter the depth number");
depth = input.nextInt() % 26;
System.out.println("ENCRYPTED TEXT IS \n" + rf.Encryption(message, depth));
break;
case 'D':
case 'd':
System.out.println("Please enter the depth number");
depth = input.nextInt() % 26;
System.out.println("DECRYPTED TEXT IS \n" + rf.Decryption(message, depth));
break;
default:
System.out.println("default case");
}
input.close();
}
}