Source Code

Source Code for EncryptFile

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Random;

 

import javax.swing.JOptionPane;

 

/**

 * Original idea from sample code found on the

 * internet http://ews.uiuc.edu/~jtimmer2/Caesar/Caesar.java

 * originally written by Mr. Ujidiku Timmermann

 *  code heavily modified by Colin Redman, 2007-2008

 *  to read file of unencrypted text and write output file

 *  and to use the GPL Ceasar Library by Valerio Capozio

 *

 */

public class EncryptFile {

  public static void main(String[] args) {

   System.out.println("Encrypted Text Generator");

  

   String message = (String)JOptionPane.showInputDialog("Copy the Text Here:");

  

   String testName = (String)JOptionPane.showInputDialog("Enter a Name for the Test").trim();

  

   //Convert input to upper case

   message = message.toUpperCase();

   //Remove all spaces

   message = message.trim(); 

  

   // create random shift

   Random generator = new Random();

   int shiftNum = generator.nextInt(26)-1;  //always non-zero

  

   Caesar caesar = new Caesar();

   //create the encoded text

   String encodedText = caesar.encodeWithoutWhiteSpace(message,shiftNum);

   String fileSeparator = System.getProperty("file.separator");

   try {

     new File(testName).mkdir();

     FileOutputStream outFile = new FileOutputStream(testName+fileSeparator+testName+".txt");

 

     PrintWriter out = new PrintWriter(outFile);

    

     out.println(encodedText);

    

     out.close();

   } catch (IOException e){

     e.printStackTrace();

   }

   System.out.println("Finished Encryption for test " + testName);

  

  

  }

 

  //Similar to encrypt code, but just removes whitespace

  private static String removeWhitespace(String message) {

   char ch;

   String res="";

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

     ch = (message.charAt(i));

     if (Character.isLetterOrDigit(ch)) {

     res += String.valueOf(ch);             

     } else {

      

     }

   }

   return res;

  

  }

}

 

 

Source Code for DecryptFile

 

/**

 * Decryption of Caesar Encrypted Text file

 * Integrated with Jazzy to check for English words to

 * detect correct decryption shift

 * Colin Redman

 * Dhaivat Panyda

 * 2007-2008 NM Supercomputer Challenge

 */

 

import java.io.BufferedReader;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.FileReader;

import java.io.IOException;

import java.io.PrintWriter;

import java.util.Vector;

 

import javax.swing.JOptionPane;

 

import com.swabunga.spell.engine.SpellDictionaryHashMap;

import com.swabunga.spell.event.SpellCheckEvent;

import com.swabunga.spell.event.SpellChecker;

 

public class DecryptFile {

 public static final String DICTIONARY_FILE = "dict/english.0";// name of

 

 // the dictionary file in the local path

 

 protected static SpellChecker spellChecker;// specllChecker object for

 

 // Jazzy

 

 static int maxWordLength = 30;//this is a guess at the largest number of characters expected in an English word

 

 public static String fileSeparator = System.getProperty("file.separator");

 

 /**

  * The raw encypted text input

  */

 String input = "";

 

 /**

  * The shifted text input

  */

 String decodedText = "";

 

 /**

  * Text with spaces (only if Jazzy returns good results)

  */

 String spacedText = "";

 

 // vector of words found

 Vector corrector = new Vector();

 

 // vector of words found plus the words NOT in the Jazzy dictionary

 Vector finalResult = new Vector();

 

 /**

  * Counts number of English words found

  */

 int wordCounter;

 

 /**

  * Calculated average word length

  */

 float aveWordLength = 0.0f;

 

 /**

  * Calculated percent of characters that are English words

  */

 float percentMatch = 0.0f;

 

 /**

  * time for the English word analysis

  */

 float calculationTime = 0.0f;

 

 String addToMessage = "";

 

 /**

  * Name of the input file without the .txt

  */

 static String inputName = "";

 

 public void doDecryption(String fileName) throws IOException {

  Caesar caesar = new Caesar();

 

  /**keeps track of best percent English word match*/

  float bestPercent = -1;

 

  /**keeps track of the shift for the best percent English word match*/

  int bestShift = -1;

 

  /**keeps track of the total calculation time for this test*/

  float totalCalculationTime = 0;

 

  /** Keep text of best decoded message*/

  String bestDecodedText = "";

  /** Keep spaced text of best decoded message */

  String bestSpacedText = "";

 

  /** keep the best final output */

  String bestFinalOutput = "";

 

  // READ The file

  input = getContents(fileName);

  System.out.println("Text read in: " + input);

  int tryShift = 0; // try 1 to start (input is always encrypted) 

 

  // Test all shifts from 1 to 25

  while (tryShift < 25) {

   tryShift++;

   aveWordLength = 0;

   percentMatch = 0;

   wordCounter = 0;

   long startTime = System.currentTimeMillis();

   decodedText = caesar.decode(input, tryShift);

   /** Here is where we test the input for English words*/

   boolean testValue = analyzeWithJazzy();

   long endTime = System.currentTimeMillis();

   long diffTime = endTime - startTime;

   calculationTime = ((diffTime) * 1.0f) / 1000.0f; //in seconds

   totalCalculationTime = totalCalculationTime + calculationTime;

   //keep track of best matches for final report

   if (percentMatch > bestPercent) {

   bestShift = tryShift;

   bestPercent = percentMatch;

   bestDecodedText = decodedText;

   bestSpacedText = spacedText;

   bestFinalOutput = finalCheck();

   }

 

   String experimentalInformation = "Experimental Information\n"

     + " Total Characters=" + input.length() + "\n"

     + " Words Matched=" + wordCounter + "\n"

     + " Average Characters Per Word=" + aveWordLength + "\n"

     + " %Word Match=" + percentMatch + "\n "

     + "Calculation Time= " + calculationTime;

   //    write the decrypted text file as an experimental result

   fileSeparator = System.getProperty("file.separator");

   try {

   FileOutputStream outFile = new FileOutputStream(inputName

     + fileSeparator + inputName + "." + tryShift + ".txt");

   PrintWriter out = new PrintWriter(outFile);

   out.println(decodedText);

   out.println(experimentalInformation);

   out.close();

   } catch (IOException e) {

   e.printStackTrace();

   }

   if (testValue == false) {

   //count = 0;

   //countLength = 0;

   //matchCount = 0;

   } else {

//write the spaced file for the results that Jazzy returns as good matches

  try {

     FileOutputStream outFile = new FileOutputStream(inputName

       + fileSeparator + inputName + ".spaced" + "."

       + tryShift + ".txt");

     PrintWriter out = new PrintWriter(outFile);

     out.println(spacedText);

     out.close();

   } catch (IOException e) {

     e.printStackTrace();

   }

 

   }

 

  }

  //Write final report

 

  try {

 

   FileOutputStream outFile = new FileOutputStream(inputName

     + fileSeparator + inputName + ".report.txt");

   PrintWriter out = new PrintWriter(outFile);

   out.println("Report for Test: " + inputName + "\n\r");

   out.println("Best Match Shift: " + bestShift + "\n\r");

   out.println("Percent Word Match: " + bestPercent + "\n\r");

   out.println("Total Calculation Time: " + totalCalculationTime);

   if (totalCalculationTime > 60) {

   long minutes = ((int) totalCalculationTime / 60);

   int seconds = (int) (totalCalculationTime - minutes * 60.0f);

   out.println(" (" + minutes + " minutes " + seconds

     + " seconds)");

   }

   out.println("\n\r");

   out.println("Original Input for Test: " + inputName + "\n\r");

   out.println(input + "\n\r");

   out.println("Decoded Text for Test: " + inputName + "\n\r");

   out.println(bestDecodedText + "\n\r");

   out.println("Spaced Text for Test: " + inputName + "\n\r");

   out.println(bestSpacedText + "\n\r");

   out.println("Final Spaced Output for Test: " + inputName + "\n\r");

   out.println(bestFinalOutput + "\n\r");

   out.close();

  } catch (IOException e) {

   e.printStackTrace();

  }

 }

 

 /**

  * This is the method that does all the work to decide if the decoded text is correct

  * @return

  * @throws IOException

  */

 protected boolean analyzeWithJazzy() {

 

  boolean isTrueDecryptedText = false;

  String lastWordFound = "";

 

  String input = decodedText;// assuming that the entire text is

// just one line - that is - not

// "newline" or "carriage return"s

 spacedText = "";

//make sure the corrector Vector is empty before we add the words to it

 corrector.clear();

 wordCounter = 0;

 int i = 0;

//iterate through to find English substrings, starting at the first character

 

 while (i < input.length()) {

   lastWordFound = "";

   for (int j = i + 1; j <= input.length(); j++) {

 

     String checking = decodedText.substring(i, j);

     if (spellChecker.isCorrect(decodedText.substring(i, j))) {

 

/**

* Now looks at next words so that if the actual word is "caterpillar" the

* search doesn't stop at cat and then the program doesn't try "erpillar".

*/

 

   String compoundWord = input.substring(i, j);

   lastWordFound = input.substring(i, j);

   int startIndex = i;

//check for a longer or compound word starting with the lastWordFound.

//if result is a blank then no additional word was found

 String result = checkForCompoundWord(compoundWord,startIndex);

  if (result != "") {

//found a compound or longer word starting with lastWordFound

   lastWordFound = result;

  }

 

  j = i + lastWordFound.length();

 

  wordCounter++;

  if (wordCounter > 1) {

   aveWordLength = ((aveWordLength * (wordCounter - 1)) + lastWordFound.length())/wordCounter;

  } else {

   aveWordLength = lastWordFound.length();

  }

 

  spacedText = spacedText + lastWordFound + " ";

  corrector.add(lastWordFound);

           i = j;

 

/*check if about 80% of the encrypted text has been searched and there are at least 1/10th the number of words as there are letters. if yes,then we found the correct decryption.

*

*/

 if (isTrueDecryptedText == false) {//only check if it is still false

  if (i >= (int) (8 * input.length() / 10)

  && wordCounter >= (int) i / 10

  && wordCounter >= 1) {

 isTrueDecryptedText = true;

       }

 }

 

 } else {

   }

 }

       i++;

  }

 

 System.out.println(finalResult.toString());

//calculate the percent match for matched words that were in the Jazzy dictionary

 percentMatch = 100.0f * (aveWordLength * (wordCounter - 1))

 / (input.length() * 1.0f);

 return isTrueDecryptedText;

  }

 

 /** This checks for longer words after an English word is found.

       * For example if ``cat" is found, and ``erpiller" immediately follows,

       * the entire word that is found is ``caterpiller".

  * Only go maxWordLength characters along to find the new longer word

  */

 protected String checkForCompoundWord(String startWord, int startIndex) {

 

  int endIndex = startIndex + startWord.length() + 1;

  String lastWordFound = "";

  int maxIndex = decodedText.length() - 1;//maximum index to go to in the text

  //check that the startWord is NOT the final word in the text

  if (decodedText.length() - startWord.length() == decodedText.indexOf(

   startWord, startIndex)) {

   return lastWordFound;

  }

  while (endIndex <= maxIndex

   && ((endIndex - startIndex) < maxWordLength)) {

 

   if (endIndex > maxIndex) {

   endIndex = maxIndex;

   }

   if (spellChecker.isCorrect(decodedText.substring(startIndex,

     endIndex))) {

   lastWordFound = decodedText.substring(startIndex, endIndex);

   }

   endIndex++;

  }

 

  return lastWordFound;

 }

 

//required for Jazzy

 public void spellingError(SpellCheckEvent event) {

 }

//required for Jazzy – initializes the spelling dictionary

 private void createDictionary() {// reads in the dictionary file so that

  // Jazzy can then use that file to check

  // spellings

 

  File dict = new File(DICTIONARY_FILE);

  try {

   spellChecker = new SpellChecker(new SpellDictionaryHashMap(dict));

  } catch (FileNotFoundException e) {

   System.err.println("Dictionary File '" + dict

     + "' not found! Quitting. " + e);

   System.exit(1);

  } catch (IOException ex) {

   System.err

     .println("IOException occurred while trying to read the dictionary file: "

       + ex);

   System.exit(2);

  }

 }

 

 /**

  * Gets the entire contents of a text file, and return it in a String.

  * @param aFile

  *            is a file which already exists and can be read.

  */

 public static String getContents(String fileName) {

 

  File inputFile = new File(fileName);

  StringBuffer contents = new StringBuffer();

 

  // declared here only to make visible to finally clause

  BufferedReader input = null;

  try {

   // use buffering, reading one line at a time

   // FileReader always assumes default encoding is OK!

   input = new BufferedReader(new FileReader(inputFile));

   String line = null; // not declared within while loop

   /*

   * readLine is a bit quirky : it returns the content of a line MINUS

   * the newline. it returns null only for the END of the stream. it

   * returns an empty String if two newlines appear in a row.

   */

   while ((line = input.readLine()) != null) {

   contents.append(line);

   contents.append(System.getProperty("line.separator"));

   }

  } catch (FileNotFoundException ex) {

   ex.printStackTrace();

  } catch (IOException ex) {

   ex.printStackTrace();

  } finally {

   try {

   if (input != null) {

     // flush and close both "input" and its underlying

     // FileReader

     input.close();

   }

   } catch (IOException ex) {

   ex.printStackTrace();

   }

  }

  return contents.toString();

 }

 

 

/** This part of the code looks back at the vector of correct words found and fills in the gaps with words that were in the decoded text but were NOT in the Jazzy library. This fixes the problem with leaving out short words that are slang, abbreviations, etc. */

 

 public String finalCheck() {

 

  int startIndex = 0;

  //make sure the finalResult Vector is empty to start

  finalResult.clear();

//If the corrector Vector has NO elements this means there were no words //found, so no use in continuing.

  if (corrector.size() != 0) {

   //Question - what if the first word in the decoded text is NOT in the corrector Vector?

   //Let's check:

   String firstWordInCorrrectorVector = (String) corrector

     .elementAt(0);

   //Is this the first word in the decodedText?

   int foundFirstWordAt = decodedText

     .indexOf(firstWordInCorrrectorVector);

   //if index is not 0, we need to use the real first word, not the first one

   //in the corrector Vector

   if (foundFirstWordAt != 0) {

   String firstWord = decodedText.substring(0, foundFirstWordAt);

   finalResult.add(firstWord);

   startIndex = foundFirstWordAt;

   }

   for (int elementCount = 0; elementCount < corrector.size(); elementCount++) {

   String word = (String) corrector.elementAt(elementCount);

   //find the index of this word in the decoded text

   int wordIndex = decodedText.indexOf(word, startIndex);

   //is it at the startIndex, or somewhere else?

   if (wordIndex == startIndex) {

     //add word to the final result Vector

     finalResult.add(word);

     startIndex = startIndex + word.length();

   } else {

     // add the text between the last found word and this one to the finalResult, then add

     // the word to the final result. Garbage is all the text between the startIndex and

     //where the next corrector word is in the decoded text

     String garbage = decodedText.substring(startIndex,

       wordIndex);

     finalResult.add(garbage);

     finalResult.add(word);

     startIndex = startIndex + garbage.length() + word.length();

   }

 

   }

   //check to see if there is some more garbage at the end and add it to the final result

 

   if (!(decodedText.endsWith((String) corrector.lastElement()))) {

   int lastIndex = decodedText.indexOf((String) corrector

     .lastElement());

   String endString = decodedText.substring(lastIndex

     + (((String) corrector.lastElement()).length()));

   finalResult.add(endString);

   }

 

  }

  //build the final output

  String output = "";

  for (int indx = 0; indx < finalResult.size(); indx++) {

   output = output + " " + (String) (finalResult.elementAt(indx));

 

  }

  return output;

 }

 

 /**

  * Decrypt the input file

  */

 public static void main(String[] args) {

  DecryptFile decrypt = new DecryptFile();

  decrypt.createDictionary();

  //enter a .txt file for decryption

  inputName = (String) JOptionPane.showInputDialog("Enter the Test Name")

   .trim();

  fileSeparator = System.getProperty("file.separator");

  try {

   decrypt

     .doDecryption(inputName + fileSeparator + inputName

       + ".txt");

  } catch (IOException e) {

   System.out.println("Cound not read input file called " + inputName

     + ".txt from directory " + inputName);

  }

 }

 

}

 

 

Caesar Library With Code Changes

 

/**

 * CesareCipher.java Classe che implementa l'algoritmo di cifratura di Cesare.

 * @author Valerio Capozio

 * @author Sito Web: http://www.angelusworld.com

 * @author Email: valeriocapozio@angelusworld.com

 */

 

/************************************************

*                  *

* Progetto: Angelus' Ciphers v 1.0       *

* Copyright 2007 Capozio Valerio *

*                  *

* Questo programma è free software e può essere *

* modificato e ridistribuito liberamente       *

* secondo i termini della licenza GPL. *

*                  *

* Per informazioni ed aggiornamenti consultare *

* il sito: http://www.angelusworld.com *

*                  *

************************************************/

 

public class Caesar {

 

private int key = 0; //this is set with a random number before the encryption

  

   /**

     * Metodo che restituisce il valore della chiave di cifratura.

     * @return int Rappresenta il valore della chiave.

     */

   public int getKey(){

       return key;

   }

  

   /**

     * Metodo che permette di settare il valore della chiave di cifratura. Di default è 3.

     * @param int k rappresenta il valore da assegnare alla chiave.

     */

   public void setKey(int k){

       this.key=k;

   }

 

   /**

     * Metodo che consente di effettuare l'operazione di cifratura su un testo passato.

     * Modified by C Redman to accept the shiftNumber

     * @param String Il testo da cifrare

     * @return  String Il testo cifrato

     */

   public String encode(String text,int shiftNum) {

       char ch;

       String res="";

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

           ch = (text.charAt(i));            

           ch = shiftSingle(ch, shiftNum);

  res += String.valueOf(ch);

 }

       return res;

   }

 

  

 

 

 

 

   /**

     * C Redman changes

     * This is the same as encode with the shift except that it works

     * on inputs without whitespace

     * @param String Il testo da cifrare

     * @return  String Il testo cifrato

     */

   public String encodeWithoutWhiteSpace(String text,int shiftNum) {

     char ch;

     String res="";

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

       ch = (text.charAt(i));            

       ch = shiftSingle(ch, shiftNum);         

       //String test = ch + "";

<