Skip to content

Commit a7ad7c8

Browse files
authored
Create ColumnarTranspositionCipher.java
Transposition cipher code in java
1 parent a163816 commit a7ad7c8

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

ColumnarTranspositionCipher.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import java.util.Arrays;
2+
import java.util.Comparator;
3+
import java.util.Scanner;
4+
5+
public class ColumnarTranspositionCipher {
6+
7+
public static String encrypt(String plaintext, String key) {
8+
int numCols = key.length();
9+
int numRows = (int) Math.ceil((double) plaintext.length() / numCols);
10+
char[][] grid = new char[numRows][numCols];
11+
int index = 0;
12+
for (int i = 0; i < numRows; i++) {
13+
for (int j = 0; j < numCols; j++) {
14+
if (index < plaintext.length()) {
15+
grid[i][j] = plaintext.charAt(index++);
16+
} else {
17+
grid[i][j] = ' ';
18+
}
19+
}
20+
}
21+
Integer[] keyOrder = new Integer[numCols];
22+
for (int i = 0; i < numCols; i++) {
23+
keyOrder[i] = i;
24+
}
25+
Arrays.sort(keyOrder, Comparator.comparingInt(i -> key.charAt(i)));
26+
StringBuilder ciphertext = new StringBuilder();
27+
for (int i : keyOrder) {
28+
for (int j = 0; j < numRows; j++) {
29+
ciphertext.append(grid[j][i]);
30+
}
31+
}
32+
return ciphertext.toString().trim();
33+
}
34+
public static void main(String[] args) {
35+
Scanner scanner = new Scanner(System.in);
36+
System.out.print("Enter the plaintext: ");
37+
String plaintext = scanner.nextLine().replaceAll("\\s+", "");
38+
System.out.print("Enter the key: ");
39+
String key = scanner.nextLine();
40+
String encryptedText = encrypt(plaintext, key);
41+
System.out.println("Encrypted Text: " + encryptedText);
42+
}
43+
}

0 commit comments

Comments
 (0)