Spring 2005

CSUDH Computer Science Department

CSC123A -01

 

Lab Assignment 8:  File Processing

Due by the end of lab session

 

Goals:

1.      Enhance the understanding of exceptions and exception handling

2.      Be able to understand Java exception handling structure

3.      Be able to write Java exception handler

4.      Be able to access Web page contents using Java

5.      Be able to consult the online API documentation

 

Exercises P15.5 on Page 610 (Playfair cipher).

 

Another way of thwarting a simple letter frequency analysis of an encrypted text is to encrypt pairs of letters together. A simple scheme to do this is the Playfir cipher. You pick a keyword and remove duplicate letters from it. Then you fill the keyword, and the remaining letters of the alphabet, into a 5 × 5 squares. (Since there are only 25 squares, I and J are considered the same letters.) Here is such an arrangement with the keyword PLAYFAIR:

      P  L A Y F

      I   R B C D

      E G H K M

      N O Q S T

      U V W X Z

 

To encrypt a letter pair, say AT, look at the rectangle with corners A and T:

 

      P  L A Y F

      I   R B C D

      E G H K M

      N O Q S T

      U V W X Z

 

The encoding of this pair is formed by looking at the other two corners of the rectangle – in this case, FQ. If both letters happen to be in the same row or column, such as GO, simply swap the two letters. Decryption is done in the same way.

 

Write a program that encrypts or decrypts an input text according to this cipher.

 

Requirements:

 

1.      Create a new project named CSC121A-Lab08.

2.      Under this project, create a PlayFairCipher that should satisfy the requirements described above. The constructor receives the key word and constructs the encryption key. The class should provide helper methods to process input file and output file, such as encrypting and decrypting characters in a reader and sending them to a writer.

3.      Create a test class PlayFairCrypt that should have a main method to parse the input arguments. Your input arguments are of the following format:

 

                               [–d] <keyword> <input.txt> <output.txt>

 

      where the option –d indicates encryption or decryption with default of encryption, <keyword> is the keyword of the cipher, and <input.txt> and <output.txt> are the input file name and the output file name respectively.

4.      Type the source code for each class as described and compile all source code and run the application. Your source code documentation must follow the instructions of Chapter 2.8, pages 54-56. Be advised to briefly comment all classes, constructors, and methods.

5.      Create a stand-alone application by exporting your source code to a folder (directory), and go to the corresponding folder to compile the source and run the byte code with the following command:

 

                              java PlayFairCrypt [–d] <keyword> <input.txt> <output.txt>

     

6.      Create all documentation files and use the web browser to display your documentation

 

Class Design:

  1. PlayFairCipher

·        Instance fields:

a.    private static final String      // the Constant

            LETTERS = "abcdefghijklmnopqrstuvwxyz";

b.    private String key; // The keyword

c.       private char[][] keys; // The encoding array

·        Constructors:

a.       Initialize the keyword to the user-entered

b.      Generate the 5×5 encryption matrix

·        Methods:

a.       processfile(File input, File output) – Read content from the input file using Reader and write the encryption/decryption to the output file using Writer, throw IOException if one of these files has problem.

b.      process(Reader r, Writer w) – Read from the Reader, encrypt/decrypt the content, write to the Writer

c.       processKeys

  1. PlayFairCrypt

·        The main method

 

Implementation:

 

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.io.File;

import java.io.Reader;

import java.io.Writer;

 

/**

   A class to encrypt and decrypt files using the Playfair cipher

 

   @author <...>

   @date <...>

*/

public class PlayfairCipher

{

   /**

      Construct a PlayfairCipher object

      @param aKey the Playfair key to use

   */  

   public PlayfairCipher(String aKey)

   {

      key = aKey;

      // To be completed

     // Generate the encryption/decryption matrix (tableau)

   }

 

   /**

      Encrypts or decrypts all characters in a file and sends

      them to another file.

      @param encrypt boolean

      @param inFile the input file

      @param outFile the output file

   */

   public void processFile(boolean encrypt, File inFile,

                         File outFile)

      throws IOException

   {

      FileReader in = null;

      FileWriter out = null;

     

      // To be completed

      // Create a FileReader and a FileWriter using the parameter

      // Call the method process to encrypt/decrypt

      // Close the reader and the writer

     

   }

  

   /**

      Encrypts or decrypts all characters in a reader and sends

      them to a writer.

      @param in the input reader

      @param out the output writer

   */

   public void process(Reader in, Writer out)

      throws IOException

   {   

      while (true)

      {

         int ic1 = in.read();

         if (ic1 == -1)

            return;

         int ic2 = in.read();

         if (ic2 == -1)

         {

            out.write(ic1);

            return;

         }

         processKeys(out, (char)ic1, (char)ic2);

       }    

      

   }

  

   /**

     * Encrypt/decrypt a pair of characters and write the result

     * to the output file

     *

     * @param Writer – the output file

     * @param char a – the 1st character of the pair

     * @param char b – the 2nd character of the pair

    */

   public void processKeys(Writer out, char a, char b)

      throws IOException

   {

     

      int r1 = -1;

      int r2 = -1;

      int c1 = -1;

      int c2 = -1;

 

      a = Character.toLowerCase(a);

      b = Character.toLowerCase(b);

      if (a == 'j')

         a = 'i';

      if (b == 'j')

         b = 'i';

 

      for (int i = 0; i < keys.length; i++)

         for (int j = 0; j < keys[i].length; j++)

         { 

            if (keys[i][j] == a)

            {

               r1 = i;

               c1 = j;

            }

            if (keys[i][j] == b)

            {

               r2 = i;

               c2 = j;

            }

         }

 

      if (r1 == -1 || r2 == -1)

      /* one of them wasn't a letter */

      { 

         out.write(a);

         out.write(b);

        

      }

      else

      {

         out.write(keys[r1][c2]);

         out.write(keys[r2][c1]);        

      }

     

   }

  

   private static final String

            LETTERS = "abcdefghijklmnopqrstuvwxyz"; 

   private String key;

   private char[][] keys;

}

 

import java.io.File;

import java.io.IOException;

 

/**

   This class tests the PlayfairCipher class

   @author <...>

   @date <...>

*/

public class PlayFairCrypt

   public static void main(String[] args)

   { 

      boolean encrypt = true;

      String key = null;

      File infile = null;

      File outfile = null;

     

      if (args.length < 3 || args.length > 4)

      {

         System.out.println

            ("Usage: java Crypt [-d] keyword infile outfile");

         System.exit(1);        

      }

 

      try

      { 

         int i;

         for (i = 0; i < args.length; i++)

         { 

            if (args[i].substring(0, 1).equals("-"))

            /* it is a command line option */

            { 

               String option = args[i].substring(1, 2);

               if (option.equals("d"))

                  encrypt = false;

            }

            else

            { 

               if (key == null)

                  key = args[i];

               else if (infile == null)

                  infile = new File(args[i]);

               else if (outfile == null)

                  outfile = new File(args[i]);

            }

         }

 

         if (infile == null || outfile == null || key == null)

         {

            System.out.println

                  ("Usage: java PlayFairCrypt

                              [-d] key infile outfile");

            System.exit(1);           

         }

        

         PlayfairCipher cipher = new PlayfairCipher(key);

         cipher.processFile(decrypt, infile, outfile);

      }

      catch (IOException e)

      { 

         System.out.println(e);

      }

   }

}

 

Exercise: