Question

Write the following cipher in java: Playfair And detail your code with comments of what each...

Write the following cipher in java:

Playfair


And detail your code with comments of what each block of code does...
0 0
Add a comment Improve this question Transcribed image text
Answer #1
// encodes text input using the Playfair cipher
// results (both encode and decode) are output
// requires a user keyword for the cipher
// ues letter 'X' for insertion, I replaces J

import java.awt.Point;
import java.util.Scanner;

public class Playfair{
  // length of digraph array
  private int length = 0;
  
  // table for Playfair cipher
  private String [][] table;
  
  // main method to test Playfair method
  public static void main(String[] args){
    Playfair pf = new Playfair();
  }
  
  // main run of the program, Playfair method
  private Playfair(){
  
    // prompts user for the keyword to use for encoding & creates tables
    System.out.println("Please input the keyword for the Playfair cipher.");
    Scanner sc = new Scanner(System.in);
    String keyword = parseString(sc);
    while(keyword.equals(""))
      keyword = parseString(sc);
    System.out.println();
    table = this.cipherTable(keyword);
    
    // prompts user for message to be encoded
    System.out.println("Please input the message to be encoded");
    System.out.println("using the previously given keyword");
    String input = parseString(sc);
    while(input.equals(""))
      input = parseString(sc);
    System.out.println();
    
    // encodes and then decodes the encoded message
    String output = cipher(input);
    String decodedOutput = decode(output);
    
    // output the results to user
    this.printTable(table);
    this.printResults(output,decodedOutput);
  }
  
  // parses any input string to remove numbers, punctuation,
  // replaces any J's with I's, and makes string all caps
  private String parseString(Scanner s){
    String parse = s.nextLine();
    parse = parse.toUpperCase();
    parse = parse.replaceAll("[^A-Z]", "");
    parse = parse.replace("J", "I");
    return parse;
  }
  
  // creates the cipher table based on some input string (already parsed)
  private String[][] cipherTable(String key){
    String[][] playfairTable = new String[5][5];
    String keyString = key + "ABCDEFGHIKLMNOPQRSTUVWXYZ";
    
    // fill string array with empty string
    for(int i = 0; i < 5; i++)
      for(int j = 0; j < 5; j++)
        playfairTable[i][j] = "";
    
    for(int k = 0; k < keyString.length(); k++){
      boolean repeat = false;
      boolean used = false;
      for(int i = 0; i < 5; i++){
        for(int j = 0; j < 5; j++){
          if(playfairTable[i][j].equals("" + keyString.charAt(k))){
            repeat = true;
          }else if(playfairTable[i][j].equals("") && !repeat && !used){
            playfairTable[i][j] = "" + keyString.charAt(k);
            used = true;
          }
        }
      }
    }
    return playfairTable;
  }
  
  // cipher: takes input (all upper-case), encodes it, and returns output
  private String cipher(String in){
    length = (int) in.length() / 2 + in.length() % 2;
    
    // insert x between double-letter digraphs & redefines "length"
    for(int i = 0; i < (length - 1); i++){
      if(in.charAt(2 * i) == in.charAt(2 * i + 1)){
        in = new StringBuffer(in).insert(2 * i + 1, 'X').toString();
        length = (int) in.length() / 2 + in.length() % 2;
      }
    }
    
    // adds an x to the last digraph, if necessary
    String[] digraph = new String[length];
    for(int j = 0; j < length ; j++){
      if(j == (length - 1) && in.length() / 2 == (length - 1))
        in = in + "X";
      digraph[j] = in.charAt(2 * j) +""+ in.charAt(2 * j + 1);
    }
    
    // encodes the digraphs and returns the output
    String out = "";
    String[] encDigraphs = new String[length];
    encDigraphs = encodeDigraph(digraph);
    for(int k = 0; k < length; k++)
      out = out + encDigraphs[k];
    return out;
  }
  
  // encodes the digraph input with the cipher's specifications
  private String[] encodeDigraph(String di[]){
    String[] enc = new String[length];
    for(int i = 0; i < length; i++){
      char a = di[i].charAt(0);
      char b = di[i].charAt(1);
      int r1 = (int) getPoint(a).getX();
      int r2 = (int) getPoint(b).getX();
      int c1 = (int) getPoint(a).getY();
      int c2 = (int) getPoint(b).getY();
      
      // case 1: letters in digraph are of same row, shift columns to right
      if(r1 == r2){
        c1 = (c1 + 1) % 5;
        c2 = (c2 + 1) % 5;
        
      // case 2: letters in digraph are of same column, shift rows down
      }else if(c1 == c2){
        r1 = (r1 + 1) % 5;
        r2 = (r2 + 1) % 5;
      
      // case 3: letters in digraph form rectangle, swap first column # with second column #
      }else{
        int temp = c1;
        c1 = c2;
        c2 = temp;
      }
      
      //performs the table look-up and puts those values into the encoded array
      enc[i] = table[r1][c1] + "" + table[r2][c2];
    }
    return enc;
  }
  
  // decodes the output given from the cipher and decode methods (opp. of encoding process)
  private String decode(String out){
    String decoded = "";
    for(int i = 0; i < out.length() / 2; i++){
      char a = out.charAt(2*i);
      char b = out.charAt(2*i+1);
      int r1 = (int) getPoint(a).getX();
      int r2 = (int) getPoint(b).getX();
      int c1 = (int) getPoint(a).getY();
      int c2 = (int) getPoint(b).getY();
      if(r1 == r2){
        c1 = (c1 + 4) % 5;
        c2 = (c2 + 4) % 5;
      }else if(c1 == c2){
        r1 = (r1 + 4) % 5;
        r2 = (r2 + 4) % 5;
      }else{
        int temp = c1;
        c1 = c2;
        c2 = temp;
      }
      decoded = decoded + table[r1][c1] + table[r2][c2];
    }
    return decoded;
  }
  
  // returns a point containing the row and column of the letter
  private Point getPoint(char c){
    Point pt = new Point(0,0);
    for(int i = 0; i < 5; i++)
      for(int j = 0; j < 5; j++)
        if(c == table[i][j].charAt(0))
          pt = new Point(i,j);
    return pt;
  }
  
  // prints the cipher table out for the user
  private void printTable(String[][] printedTable){
    System.out.println("This is the cipher table from the given keyword.");
    System.out.println();
    
    for(int i = 0; i < 5; i++){
      for(int j = 0; j < 5; j++){
        System.out.print(printedTable[i][j]+" ");
      }
      System.out.println();
    }
    System.out.println();
  }
  
  // prints results (encoded and decoded)
  private void printResults(String enc, String dec){
    System.out.println("This is the encoded message:");
    System.out.println(enc);
    System.out.println();
    System.out.println("This is the decoded message:");
    System.out.println(dec);
  }
}
Add a comment
Know the answer?
Add Answer to:
Write the following cipher in java: Playfair And detail your code with comments of what each...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • . Please write a function that will do the following Decryption of a message encrypted with a substitution cipher given cipher text only without any key Please provide comments on each line of code ou...

    . Please write a function that will do the following Decryption of a message encrypted with a substitution cipher given cipher text only without any key Please provide comments on each line of code outlining what that line is doing. Note: Only the Function is to be written, all user inputs i.e the text to be decrypted will be entered earlier in the program. Code must be written in C and be able to be compiled using GCC If any...

  • PLEASE UPLOAD or Write a simple PSEUDO CODE AND JAVA CODE for this program WITH COMMENTS...

    PLEASE UPLOAD or Write a simple PSEUDO CODE AND JAVA CODE for this program WITH COMMENTS IN BOTH TELLING WHAT EACH PART DOES. (I NEED BOTH CODES NOT JUST ONE OR THE OTHER) Problem Statement A golf club has a small tournament consisting of five golfers every weekend. The club president has asked you to design a program that does the following: Reads player’s names and their scores from the keyboard for each of the five golfers and simulates writing...

  • Write a java code that will Implement Simple Substitution cipher with permutations and Implement Letter Frequency...

    Write a java code that will Implement Simple Substitution cipher with permutations and Implement Letter Frequency Analysis. As well as Apply Letter Frequency Analysis to chosen outputs of your Simple Substitution encryption.

  • Can i get Playfair Cipher for python 3 that encrypts a message and decrypts it, could...

    Can i get Playfair Cipher for python 3 that encrypts a message and decrypts it, could you possibly make it as simple as you can without losing functionality. please include comments, that would help me better understand Example of PlayFair Cipher: https://en.wikipedia.org/wiki/Playfair_cipher The Playfair cipher uses a 5 by 5 table containing a key word or phrase. Memorization of the keyword and 4 simple rules was all that was required to create the 5 by 5 table and use the...

  • Java programming. Introduction to Classes and Methods. Please write the correct code, with comments so I...

    Java programming. Introduction to Classes and Methods. Please write the correct code, with comments so I can understand what you did, and please make the code as SIMPLE as possible -- this is an intro to Classes/Methods practice. If your answer is right, I will give you thumbs up rating! Each of the following methods should be static and defined in a class called Utilities. Implement a second class calledTester that calls each of these methods

  • in BASIC/BEGINNER OBJECT ORIENTATED JAVA Please write code for the following program using comments explaining the...

    in BASIC/BEGINNER OBJECT ORIENTATED JAVA Please write code for the following program using comments explaining the code. (You can hand write this). Give a UML example illustrating AGGREGATION. Include classes, fields, methods, instance fields. USE ONE SUPER CLASS AND TWO SUB CLASSES. Include pcode for at least one method of each class. Explain the whole part relationship and if this a deep or shallow copy.

  • JAVA CODE Topic: BST Animation For each task, submit the source code with detail comments. Objective:...

    JAVA CODE Topic: BST Animation For each task, submit the source code with detail comments. Objective: javafx GUI program for BST Animation. BSTAnimation.java, AbstractTree.java and Tree.java. Modify the BSTAnimation.java  (1) Add Show Preoreder and Show Postorder button. Insert these two buttons next to the Show Inorder button to display tree in selected order. (2) Currently removing node method is to replace the removed node by the highest node on left-subtree. Modify the method by using lowest node on the right-subtree instead....

  • Please do in java as simply as possible with code available for copy and comments Write...

    Please do in java as simply as possible with code available for copy and comments Write a program that reads a file (provided as attachment to this assignment) and writes the file to a different file with line numbers inserted at the beginning of each line. Throw an exception if the file does not exist. An error message should result. For example if file input is: This is a test File output should be 1. This is a test I...

  • 2. (10 pts) For the following code, write comments to describe what is being selected by...

    2. (10 pts) For the following code, write comments to describe what is being selected by the following code ( see MSP430x5xx User's Guide, ch. 28, p. 742-747, and the functional block diagram on the previous page) ADC12CTLO ISREF 0; ADC12CTLO I-ADC12SHT 2; ADC12CTL ADC12DIV 0; ADC12CTL -CONSEQ 0; ADC12CTL ADC12CSTARTADD1; ADC12CTLO ADC12SC;

  • Write a java program that takes the following phrases and encrypts them using a substitution cipher....

    Write a java program that takes the following phrases and encrypts them using a substitution cipher. The program should ask for a key and a phrase and then proceed to encrypt that phrase using the given shared key. Make sure that you have the key for the cipher and the output of encrypted phrases. Encrypt the phrase: He who fights with monsters should look to it that he himself does not become a monster. And if you gaze long into...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT