From 254cc94b85d6732e3c119d8a832179f08a79a4c9 Mon Sep 17 00:00:00 2001 From: Dilrose Reji <70878223+dilroseR@users.noreply.github.com> Date: Tue, 12 Oct 2021 11:45:35 +0530 Subject: [PATCH] Add product cipher (#2529) --- Ciphers/ProductCipher.java | 72 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) create mode 100644 Ciphers/ProductCipher.java diff --git a/Ciphers/ProductCipher.java b/Ciphers/ProductCipher.java new file mode 100644 index 000000000..ce6b088d7 --- /dev/null +++ b/Ciphers/ProductCipher.java @@ -0,0 +1,72 @@ +package Ciphers; + +import java.util.Scanner; + +class ProductCipher { + + public static void main(String args[]) { + Scanner sc = new Scanner(System.in); + System.out.println("Enter the input to be encrypted: "); + String substitutionInput = sc.nextLine(); + System.out.println(" "); + System.out.println("Enter a number: "); + int n = sc.nextInt(); + + // Substitution encryption + StringBuffer substitutionOutput = new StringBuffer(); + for (int i = 0; i < substitutionInput.length(); i++) { + char c = substitutionInput.charAt(i); + substitutionOutput.append((char) (c + 5)); + } + System.out.println(" "); + System.out.println("Substituted text: "); + System.out.println(substitutionOutput); + + // Transposition encryption + String transpositionInput = substitutionOutput.toString(); + int modulus; + if ((modulus = transpositionInput.length() % n) != 0) { + modulus = n - modulus; + + for (; modulus != 0; modulus--) { + transpositionInput += "/"; + } + } + StringBuffer transpositionOutput = new StringBuffer(); + System.out.println(" "); + System.out.println("Transposition Matrix: "); + for (int i = 0; i < n; i++) { + for (int j = 0; j < transpositionInput.length() / n; j++) { + char c = transpositionInput.charAt(i + (j * n)); + System.out.print(c); + transpositionOutput.append(c); + } + System.out.println(); + } + System.out.println(" "); + System.out.println("Final encrypted text: "); + System.out.println(transpositionOutput); + + // Transposition decryption + n = transpositionOutput.length() / n; + StringBuffer transpositionPlaintext = new StringBuffer(); + for (int i = 0; i < n; i++) { + for (int j = 0; j < transpositionOutput.length() / n; j++) { + char c = transpositionOutput.charAt(i + (j * n)); + transpositionPlaintext.append(c); + } + } + + // Substitution decryption + StringBuffer plaintext = new StringBuffer(); + for (int i = 0; i < transpositionPlaintext.length(); i++) { + char c = transpositionPlaintext.charAt(i); + plaintext.append((char) (c - 5)); + } + + System.out.println("Plaintext: "); + System.out.println(plaintext); + sc.close(); + } + +}