From 0ff7708311014b2bbb4923708790824d3b1a3b33 Mon Sep 17 00:00:00 2001 From: Madhav tripathi Date: Fri, 1 Oct 2021 17:41:52 +0530 Subject: [PATCH] Added transposition cipher --- Java/TranspositionCipher/Main.class | Bin 0 -> 5173 bytes Java/TranspositionCipher/Main.java | 444 ++++++++++++++++++ .../TranspositionCipher.class | Bin 0 -> 3640 bytes Java/TranspositionCipher/decrypted.txt | 1 + Java/TranspositionCipher/encrypted.txt | 1 + Java/TranspositionCipher/plain.txt | 1 + Java/TranspositionCipher/readme.md | 10 + 7 files changed, 457 insertions(+) create mode 100644 Java/TranspositionCipher/Main.class create mode 100644 Java/TranspositionCipher/Main.java create mode 100644 Java/TranspositionCipher/TranspositionCipher.class create mode 100644 Java/TranspositionCipher/decrypted.txt create mode 100644 Java/TranspositionCipher/encrypted.txt create mode 100644 Java/TranspositionCipher/plain.txt create mode 100644 Java/TranspositionCipher/readme.md diff --git a/Java/TranspositionCipher/Main.class b/Java/TranspositionCipher/Main.class new file mode 100644 index 0000000000000000000000000000000000000000..9983b7e2ccd4a735559fe814b241ce8258e32940 GIT binary patch literal 5173 zcmb7I3wRt=75>j=lbLL`O}kB7lD2dTElv7Jnl>$v7FwG&Hf#BhxaUzXw82zKJS2(HIhRD4z5Hz>GK z!A&CWYY|Mx%?fUb;4qve;9r;F8!Emj@AFjjskl|ew^ZDw;@c{|qvCeq`L2rZi4NbF zk6kKutGGj^KMe^l@%LeVnIw!C8r1(j7B3E>7OZW2nHE!%9(^lUcW z4t;ZyR|-?EWqX8)mCal9ZF)^ox4UcFJznfyDvXN1pR@_8KQmpIa7aG!>g|S^@+`;p z>D9PtIIiw7bhxrX5XQ87y0NuIPX!W7jHIc%?S^ZbHiwNxbemp_X=gZq95xO+Au zR`57O_2?F>Fsbsy(X?dOu?Lu|-O0Fy*=UJj#VyQIEjC4AqD#S_qj&;OD)>tj7PdsO zRfc_dk}&yT%U5QsWZYy!OIN$D<7$p!WLz^|uSM|`o|fUSQTz@26+9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$AjVYt0gMqIw&v<2zB_DB)*0KWq45|It)_&dBbIqYr*)Uu*#b z77U=4@fL21Ey^Mw4sXN&8@x4$VTI4}>8zlYfuQ>0Si?t1TIKW23M7>mi>SudoTyK-nE3~b zS|coYCAOBOv%JOig|T(HX;G{>Hx<(g`_a-oXh69#ue_)qtvfL-C!meNWi2qK57+O- z`p(#fJvi>3|5rd`Yq>K2U;*t13#iW%&>{XiUWSb_Y?9$qJd~l+w{dLjME~m~`Fd}_ zk1>}8YQzSfzk?DAp^OSKnVZe2q+kZAID(2XmwS%|RD#76MLmtdavFcRyq{7({$WHGjJCjhI{F7+)p#{AkD(VG#ign7533wyh`)& z7FF}lhXvgEFX9fjj-s@fVzh)N(~&fdj;7gEPxELg)zUIvIflPh&~jQyO|*(mrbdd> z8rni@sfSv~rB>Qb>*);IK<83BT|galDQ%={XcOH?opc+WK=;u}^bl>PN64VZ$)tVM zMbA)zo+pc5q^Uq#nQ$6!W@*ZL;hS8Lk-zQ0uP`()(*i zB9g@zr1U2Tuy7ROjX7YU;V1Vm3t#+U9QowT_dy&p-sYOr%POi|ownn%{J%#RVh2tQ z%IGCrE~H>+1NclIrZ#h-=i+{HAI3MwbWXZHsLi~vc^7kopCaa$_jpE HLTCOD>-;za literal 0 HcmV?d00001 diff --git a/Java/TranspositionCipher/Main.java b/Java/TranspositionCipher/Main.java new file mode 100644 index 00000000..864d1b57 --- /dev/null +++ b/Java/TranspositionCipher/Main.java @@ -0,0 +1,444 @@ +import static java.lang.System.*;//as it's static we don't need to write System repeatedly +import java.util.*; +import java.io.*; +// import ciphers.transposition_cipher.TranspositionCipher; : not working + +/** + * Mini-Project for implementing different crypto algorithms + */ + +class TranspositionCipher { + + public boolean checkKey(String key) { + + try { + // check key length + if (!(key.length() < 10)) { + throw new Exception("Key is too long. Only allow cipher keys with length up to 10."); + } + // will throw an exception for non-numeric value + int keyInInt = Integer.parseInt(key); + + /*if (checkForRepeatedDigitInKey(key) && checkForMissingKeyValue(key)) { + return true; + }*/ + + if(checkKeyDigits(key) && key.contains("0")) + { + return true; + } + + } catch (NumberFormatException nfe) { + err.println("Please enter Integer value"); + } + + catch (Exception e) { + err.println("Exception: " + e.getMessage()); + } + + return false; + } + + /*public static boolean checkForMissingKeyValue(String key) { + int keyLength = key.length(); + + for (int i = 0; i < keyLength; i++) { + if (!key.contains(Integer.toString(i))) { + System.out.println("Each digit of key must be within the range from 0 to the length of the key."); + return false; + } + } + return true; + } + + public static boolean checkForRepeatedDigitInKey(String key) { + // needs to check whether each number in the key is unique. + String curDigit = ""; + for (int i = 0; i < key.length(); i++) { + if (i < key.length() - 1) { + curDigit = key.substring(i, i + 1); + String restOfKey = key.substring(i + 1); + if (restOfKey.contains(curDigit)) { + System.out.println("Cannot have recurring numbers."); + return false; + } + } + } + return true; + }*/ + + public static boolean checkKeyDigits(String key) + { + int N = key.length(); + int sum = 0; + int digit = 0; + for (int i = 0; i < N; i++) + { + digit = Integer.parseInt(Character.toString(key.charAt(i))); + sum += digit; + } + int expectedSum = ((N)*(N-1)/2); + System.out.println(Integer.toString(sum)); + System.out.println(Integer.toString(expectedSum)); + if(sum == expectedSum) + return true; + else + return false; + } + + // function for reading a file + public String readFromInputFile(String inputFilename) { + String lines = ""; + String content = ""; + + try { + BufferedReader fileReader = new BufferedReader(new FileReader(inputFilename)); + + lines = fileReader.readLine(); + + while (lines != null) { + content = content + lines; + + if ((lines = fileReader.readLine()) != null) { + content = content + " "; + } + } + + fileReader.close(); + return content; + + } catch (IOException ioe) { + System.out.println("Error reading file."); + } + return lines; + } + + public boolean writeToOutputFile(String data, String outputFilename) { + + try { + PrintWriter pw = new PrintWriter(outputFilename); + pw.print(data); + pw.close(); + return true; + } catch (IOException ioe) { + System.out.println("Failed to write to output file."); + } + + return false; + + } + + public String encryptUsingTransposition(String input, String key) { + + int numberOfCols = key.length(); + int numberOfRows = 0; + + if (input.length() % numberOfCols > 0) { + numberOfRows = (input.length() / numberOfCols) + 1; + } + + if (input.length() % numberOfCols == 0) { + numberOfRows = input.length() / numberOfCols; + } + + char[][] characterMap; + characterMap = new char[numberOfRows][numberOfCols]; + + for (int row = 0; row < numberOfRows; row++) { + for (int col = 0; col < numberOfCols; col++) { + characterMap[row][col] = ' '; + } + } + int rows = 0; + int cols = 0; + + for (int i = 0; i < input.length(); i++) { + characterMap[rows][cols] = input.charAt(i); + cols++; + if (cols == numberOfCols) { + rows++; + cols = 0; + } + } + + // need to append back into a string according to the key. + int curCols = 0; + String result = ""; + + for (int i = 0; i < key.length(); i++) { + + if (i == key.length() - 1) { + curCols = Integer.parseInt(key.substring(i)); + } else { + curCols = Integer.parseInt(key.substring(i, i + 1)); + } + + for (int k = 0; k < numberOfRows; k++) { + result = result + characterMap[k][curCols]; + } + + } + + return result; + } + + public String decryptUsingTransposition(String data, String key) { + int numberOfCols = key.length(); + int numberOfRows = 0; + + if (data.length() % numberOfCols > 0) { + numberOfRows = (data.length() / numberOfCols) + 1; + } + + if (data.length() % numberOfCols == 0) { + numberOfRows = data.length() / numberOfCols; + } + + char[][] characterMap = new char[numberOfRows][numberOfCols]; + + for (int row = 0; row < numberOfRows; row++) { + for (int col = 0; col < numberOfCols; col++) { + characterMap[row][col] = ' '; + } + } + + int curCols = 0; + int dataIndex = 0; + String result = ""; + + // Fills up the columns of the characterMap by column. + for (int i = 0; i < key.length(); i++) { + if (i == key.length() - 1) { + curCols = Integer.parseInt(key.substring(i)); + } else { + curCols = Integer.parseInt(key.substring(i, i + 1)); + } + + for (int k = 0; k < numberOfRows; k++) { + if (dataIndex < data.length()) { + characterMap[k][curCols] = data.charAt(dataIndex); + dataIndex++; + } + } + } + + // Reads characterMap left to right, from row 0 to last row. + for (int row = 0; row < numberOfRows; row++) { + for (int col = 0; col < numberOfCols; col++) { + result = result + characterMap[row][col]; + } + } + + return result; + + } + +} + +public class Main { + + // just so that we don't have to write sop repeatedly + + public static void print(String str) { + System.out.print(str); + } + + public static void println(String str) { + System.out.println(str); + } + + public void printerr(Exception e) { + err.println("Error occured: " + e); + } + + public static void decorate(char c) { + for (int i = 0; i < 36; i++) { + print(Character.toString(c)); + } + + } + + // source: stackOverflow + public static void clearScreen() { + try { + // for windows + if (System.getProperty("os.name").contains("Windows")) + new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor(); + // for linux based O.S + else + Runtime.getRuntime().exec("clear"); + } catch (Exception ex) { + } + } + + public static void getMenu() throws InterruptedException, InputMismatchException, IOException { + Scanner scan = new Scanner(System.in); + String plainText; + String encryptedText; + String decryptedText; + String key; + String inputFile; + String outputFile; + TranspositionCipher tCipher = new TranspositionCipher(); + do { + + clearScreen(); + decorate('-'); + println("\nChoose one of the following options:"); + decorate('-'); + println("\n0. Exit"); + println("1. Encrypt Text using Transposition Cipher"); + println("2. Decrypt Text using Transposition Cipher"); + println("3. Encrypt File using Transposition Cipher"); + println("4. Decrypt File using Transposition Cipher"); + println("11. Rules for selecting Transposition key"); + print("Enter your option : "); + int option = scan.nextInt(); + + switch (option) { + + case 0: + println("Exiting......"); + System.exit(0); + + case 1: + scan.nextLine(); // because as we press enter after selecting the option it might read it as out + // plain text + print("Enter Text to be Encrypted : "); + plainText = scan.nextLine(); + + print("Enter an integer key (checkout option 11 for rules of choosing a key) : "); + key = scan.next(); + + if (!tCipher.checkKey(key)) { + println("Incorrect Key check out option 11"); + println("refreshing in 3 seconds..."); + Thread.sleep(2000); + break; + } + println("key is correct"); + + encryptedText = tCipher.encryptUsingTransposition(plainText, key); + + println("Encrypted text is : " + encryptedText); + + print("Screen will automatically refresh in 4 seconds...."); + Thread.sleep(4000); + + break; + + case 2: + scan.nextLine(); // same as above + print("Enter Text to be Decrypted : "); + final String enText = scan.nextLine(); + print("Enter the key which you previously entered : "); + key = scan.next(); + + if (!tCipher.checkKey(key)) { + println("Incorrect Key check out option 11"); + println("refreshing in 3 seconds..."); + Thread.sleep(3000); + break; + } + + println("key is correct"); + + decryptedText = tCipher.decryptUsingTransposition(enText, key); + + println("Decrypted text is : " + decryptedText); + + print("Screen will automatically refresh in 4 seconds...."); + + Thread.sleep(6000); + + break; + + case 3: + println("Enter Input File Name : "); + inputFile = scan.next(); + + println("Enter Output File Name : "); + outputFile = scan.next(); + + println("Enter Key : "); + key = scan.next(); + + if (!tCipher.checkKey(key)) { + println("Incorrect Key check out option 11"); + println("refreshing in 3 seconds..."); + Thread.sleep(2000); + break; + } + println("key is correct"); + + plainText = tCipher.readFromInputFile(inputFile); + encryptedText = tCipher.encryptUsingTransposition(plainText, key); + + if (tCipher.writeToOutputFile(encryptedText, outputFile)) { + println("successfully copied Encrypted message to " + outputFile); + } else { + throw new IOException("IO exception file output error "); + } + + break; + + case 4: + println("Enter Input File Name : "); + inputFile = scan.next(); + + println("Enter Output File Name : "); + outputFile = scan.next(); + + println("Enter Key : "); + key = scan.next(); + + if (!tCipher.checkKey(key)) { + println("Incorrect Key check out option 11"); + println("refreshing in 3 seconds..."); + Thread.sleep(2000); + break; + } + println("key is correct"); + + plainText = tCipher.readFromInputFile(inputFile); + decryptedText = tCipher.decryptUsingTransposition(plainText, key); + + if (tCipher.writeToOutputFile(decryptedText, outputFile)) { + println("successfully copied Decrypted message to " + outputFile); + } else { + throw new IOException("IO exception file output error "); + } + + break; + + case 11: + println("Rules for selecting a key : "); + println("1. Key shouldn't be too long, allowing cipher keys with length up to 10."); + println("2. It shouldn't have recurring numbers."); + println("3. Each digit of key must be within the range from 0 to the length of the key."); + println("refreshing in 5 seconds..."); + Thread.sleep(5000); + + break; + default: + println("Enter a valid option :) "); + Thread.sleep(1000); + break; + } + + } while (true); + + } + + public static void main(String... args) { + try { + getMenu(); + } catch (IOException ioe) { + err.println(ioe); + } catch (InputMismatchException ime) { + println("Enter one of the valid option"); + } catch (Exception exception) { + exception.printStackTrace(); + } + } +} \ No newline at end of file diff --git a/Java/TranspositionCipher/TranspositionCipher.class b/Java/TranspositionCipher/TranspositionCipher.class new file mode 100644 index 0000000000000000000000000000000000000000..da6e36e2051642984c13b5bea43c75755f482927 GIT binary patch literal 3640 zcmcIm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