Skip to content

Commit 254cc94

Browse files
authored
Add product cipher (TheAlgorithms#2529)
1 parent bcdf7d6 commit 254cc94

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Ciphers/ProductCipher.java

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package Ciphers;
2+
3+
import java.util.Scanner;
4+
5+
class ProductCipher {
6+
7+
public static void main(String args[]) {
8+
Scanner sc = new Scanner(System.in);
9+
System.out.println("Enter the input to be encrypted: ");
10+
String substitutionInput = sc.nextLine();
11+
System.out.println(" ");
12+
System.out.println("Enter a number: ");
13+
int n = sc.nextInt();
14+
15+
// Substitution encryption
16+
StringBuffer substitutionOutput = new StringBuffer();
17+
for (int i = 0; i < substitutionInput.length(); i++) {
18+
char c = substitutionInput.charAt(i);
19+
substitutionOutput.append((char) (c + 5));
20+
}
21+
System.out.println(" ");
22+
System.out.println("Substituted text: ");
23+
System.out.println(substitutionOutput);
24+
25+
// Transposition encryption
26+
String transpositionInput = substitutionOutput.toString();
27+
int modulus;
28+
if ((modulus = transpositionInput.length() % n) != 0) {
29+
modulus = n - modulus;
30+
31+
for (; modulus != 0; modulus--) {
32+
transpositionInput += "/";
33+
}
34+
}
35+
StringBuffer transpositionOutput = new StringBuffer();
36+
System.out.println(" ");
37+
System.out.println("Transposition Matrix: ");
38+
for (int i = 0; i < n; i++) {
39+
for (int j = 0; j < transpositionInput.length() / n; j++) {
40+
char c = transpositionInput.charAt(i + (j * n));
41+
System.out.print(c);
42+
transpositionOutput.append(c);
43+
}
44+
System.out.println();
45+
}
46+
System.out.println(" ");
47+
System.out.println("Final encrypted text: ");
48+
System.out.println(transpositionOutput);
49+
50+
// Transposition decryption
51+
n = transpositionOutput.length() / n;
52+
StringBuffer transpositionPlaintext = new StringBuffer();
53+
for (int i = 0; i < n; i++) {
54+
for (int j = 0; j < transpositionOutput.length() / n; j++) {
55+
char c = transpositionOutput.charAt(i + (j * n));
56+
transpositionPlaintext.append(c);
57+
}
58+
}
59+
60+
// Substitution decryption
61+
StringBuffer plaintext = new StringBuffer();
62+
for (int i = 0; i < transpositionPlaintext.length(); i++) {
63+
char c = transpositionPlaintext.charAt(i);
64+
plaintext.append((char) (c - 5));
65+
}
66+
67+
System.out.println("Plaintext: ");
68+
System.out.println(plaintext);
69+
sc.close();
70+
}
71+
72+
}

0 commit comments

Comments
 (0)