-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimpleColumnarTransposition.java
More file actions
64 lines (64 loc) · 2.51 KB
/
SimpleColumnarTransposition.java
File metadata and controls
64 lines (64 loc) · 2.51 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
import java.util.Arrays;
import java.util.Scanner;
public class SimpleColumnarTransposition {
public static String encrypt(String plaintext, String key) {
int[] keyOrder = getKeyOrder(key);
int rows = (int) Math.ceil((double) plaintext.length() / key.length());
char[][] grid = new char[rows][key.length()];
// Fill grid with plaintext
int index = 0;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < key.length(); j++) {
grid[i][j] = (index < plaintext.length()) ? plaintext.charAt(index++) : 'X';
}
}
// Read columns based on key order
StringBuilder ciphertext = new StringBuilder();
for (int col : keyOrder) {
for (int i = 0; i < rows; i++) {
ciphertext.append(grid[i][col]);
}
}
return ciphertext.toString();
}
public static String decrypt(String ciphertext, String key) {
int[] keyOrder = getKeyOrder(key);
int rows = ciphertext.length() / key.length();
char[][] grid = new char[rows][key.length()];
// Fill grid column by column based on key order
int index = 0;
for (int col : keyOrder) {
for (int i = 0; i < rows; i++) {
grid[i][col] = ciphertext.charAt(index++);
}
}
// Read rows to get plaintext
StringBuilder plaintext = new StringBuilder();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < key.length(); j++) {
plaintext.append(grid[i][j]);
}
}
return plaintext.toString();
}
private static int[] getKeyOrder(String key) {
int[] order = new int[key.length()];
Character[] chars = new Character[key.length()];
for (int i = 0; i < key.length(); i++) chars[i] = key.charAt(i);
Arrays.sort(chars, (a, b) -> a.compareTo(b));
for (int i = 0; i < chars.length; i++) order[i] = key.indexOf(chars[i]);
return order;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter plaintext: ");
String plaintext = sc.nextLine();
System.out.print("Enter key: ");
String key = sc.nextLine();
String ciphertext = encrypt(plaintext, key);
System.out.println("Ciphertext: " + ciphertext);
String decryptedText = decrypt(ciphertext, key);
System.out.println("Decrypted text: " + decryptedText);
sc.close();
}
}