-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathColoumnar.java
128 lines (106 loc) · 3.54 KB
/
Coloumnar.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
import java.util.*;
import java.io.*;
import java.lang.*;
public class Coloumnar{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String line = System.getProperty("line.separator");
scan.useDelimiter(line);
System.out.print("1. Encryt 2.Decrypt : ");
int option = scan.nextInt();
switch (option) {
case 1:
System.out.print("Enter String:");
String text = scan.next();
System.out.print("Enter Key:");
String key = scan.next();
System.out.println(encryptCT(key, text).toUpperCase());
break;
case 2:
System.out.print("Enter Encrypted String:");
text = scan.next();
System.out.print("Enter Key:");
key = scan.next();
System.out.println(decryptCT(key, text));
break;
default:
break;
}
}
public static String encryptCT(String key, String text) {
int[] arrange = arrangeKey(key);
int lenkey = arrange.length;
int lentext = text.length();
int row = (int) Math.ceil((double) lentext / lenkey);
char[][] grid = new char[row][lenkey];
int z = 0;
for (int x = 0; x < row; x++) {
for (int y = 0; y < lenkey; y++) {
if (lentext == z) {
// at random alpha for trailing null grid
grid[x][y] = RandomAlpha();
z--;
} else {
grid[x][y] = text.charAt(z);
}
z++;
}
}
String enc = "";
for (int x = 0; x < lenkey; x++) {
for (int y = 0; y < lenkey; y++) {
if (x == arrange[y]) {
for (int a = 0; a < row; a++) {
enc = enc + grid[a][y];
}
}
}
}
return enc;
}
public static String decryptCT(String key, String text) {
int[] arrange = arrangeKey(key);
int lenkey = arrange.length;
int lentext = text.length();
int row = (int) Math.ceil((double) lentext / lenkey);
String regex = "(?<=\\G.{" + row + "})";
String[] get = text.split(regex);
char[][] grid = new char[row][lenkey];
for (int x = 0; x < lenkey; x++) {
for (int y = 0; y < lenkey; y++) {
if (arrange[x] == y) {
for (int z = 0; z < row; z++) {
grid[z][y] = get[arrange[y]].charAt(z);
}
}
}
}
String dec = "";
for (int x = 0; x < row; x++) {
for (int y = 0; y < lenkey; y++) {
dec = dec + grid[x][y];
}
}
return dec;
}
public static char RandomAlpha() {
//generate random alpha for null space
Random r = new Random();
return (char)(r.nextInt(26) + 'a');
}
public static int[] arrangeKey(String key) {
//arrange position of grid
String[] keys = key.split("");
Arrays.sort(keys);
int[] num = new int[key.length()];
for (int x = 0; x < keys.length; x++) {
for (int y = 0; y < key.length(); y++) {
if (keys[x].equals(key.charAt(y) + "")) {
num[y] = x;
break;
}
}
}
return num;
}
}