Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2 Encryption In this assignment, you will implement a very crude encryption algo

ID: 3854102 • Letter: 2

Question

2 Encryption

In this assignment, you will implement a very crude encryption algorithm. Each byte of a file will be increased by a varying value based on a password.

User Input

A dialog asks which existing file to open
JFileChooser fileChooser = new JFileChooser(); File inputFile = null; if (fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) { inputFile = fileChooser.getSelectedFile(); } 2.1.2 A dialog asks if you want to encrypt or decrypt the input file String[] commands = { "encrypt", "decrypt" }; String command = (String) JOptionPane.showInputDialog(null, "What would you like to do?", "Commands", JOptionPane.QUESTION_MESSAGE, null, commands, commands[0]); 1 2.1.3 A dialog asks for a file to save the output The difference with the other file dialog we did, is the name of the function. This one allows us to specify a new filename for a file that doesn’t exists yet. You can reuse the same file chooser if you want. This will leave it in the folder the user last was in.

File outputFile = null; if (fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { outputFile = fileChooser.getSelectedFile(); }

2.1.4 A dialog asks for the password to use String password = JOptionPane.showInputDialog("Password");

2.1.5 At the end, a message shows the task was done JOptionPane.showMessageDialog(null, "All Done.");

2.2 Open the File Streams
When opening a file for reading or writing, many things can go wrong in the form of IOException. This is why you need to decide what to do when things go wrong by using try-catch blocks.

try { // open the files InputStream in = new FileInputStream(inputFile); OutputStream out = new FileOutputStream(outputFile);
// TODO read/write bytes in.close(); out.close(); } catch (IOException e) {
// TODO decide what to do when something goes wrong }

2.3 Handling Errors
If your program crashes due to NullPointerException, you can: 2 • Check your variables for null before using them. Maybe bailing out early if so (with a message to the user). if(inputFile == null) { JOptionPane.showMessageDialog(null, "Invalid inputFile."); return; } • catch all Exception try { ... } catch (IOException e) { // TODO decide what to do when I/O goes wrong } catch (Exception e) { // TODO decide what to do when something else goes wrong }

2.3.1 Message to the user
In this assignment, it’s a good idea to let the user know about the problem.


2.4 Reading and writing one byte at a time
The standard loop for reading from an input stream is a bit cryptic, but if you read it slowly, you will understand that it stores the value read from the file in a variable, and then test if it was -1 which indicates end of file. int value; while ((value = in.read()) != -1) { // do something with the value which is between [0, 255] // write a byte out.write(value); }

2.5 Encrypt or Decrypt one byte
If you want to increase the byte read by 3, you would need to do: // encrypt the byte value += 3; while(value >= 256) value -= 256; // keep the value between [0, 255] If you want to decrease the byte read by 3, you would need to do: // decrypt the byte value -= 3; while(value < 0) value += 256; // keep the value between [0, 255] This assignment requires you to use a password, instead of a hardcoded value like 3. If the password is "hel", the value you should increment or decrement by are: 104 // value of character ’h’ as an integer 101 // value of character ’e’ as an integer 108 // value of character ’l’ as an integer 104 // value of character ’h’ as an integer 101 // value of character ’e’ as an integer 3 etc... // decrypt the byte value -= password.charAt(passIndex); // where passIndex is an integer that cycles from 0 to password.length() - 1.

2.6 Sample Encrypted File
The file secret.txt was encrypted using the password: cst8110 (lowercase). Test your decrypt function with it. The result should be plain text.

2.7 Bonus: Performance If you try to encrypt and decrypt a large file, you will find the performance lacking (i.e. it will take several seconds, if not minutes, depending on the size of the file). This is because each time we call read() or write(), the request is passed to the Operating System, which will ask the File System to give or write a byte to disk. It’s better for performance to do these request infrequently. So instead of doing things one byte at a time, it would be better to do them in batch, using one of the byte array read() or write() variants. This would mean that you would have to make your code more complex though. An alternate solution is to wrap the input and output streams in buffered streams. The idea is that the buffered stream object will do things in batch using the array functions for you. When you call read(), it will only have to ask the Operating System when its array is empty. When you call write(), it will only have to notify the Operating System when its array is full, or when you flush() or close(). Figure out how to use BufferedInputStream, and the BufferedOutputStream objects from the java.io package. Note: closing the wrapper stream will close the underlying stream. In other words, you only have to close your buffered stream

Explanation / Answer

Here is the code for the question. To test

1. Run the application. Choose a input file say "input1.txt" and select encrypt , specify password and save it as say "output1.txt"

2. Run the application again. Choose the "output1.txt" from previous step and but select decrypt , and specify the same password as in step 1. Lets say you save the file as output2.txt

Now if encryption and decryption worked corrrectly , the input file in step1 should match the output file in step2. ie. output2.txt should be same as input1.txt

In case of any issues/ doubts , please post a comment, I shall respond. If happy with the answer , please rate it. Thank you

==============

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import javax.swing.JFileChooser;

import javax.swing.JOptionPane;

public class EncryptDecryptFile {

   private static JFileChooser fileChooser = new JFileChooser();

  

     

   private static File getUserInputFile()

   {

       if(fileChooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)

           return fileChooser.getSelectedFile();

       else

           return null;

   }

   private static File getUserOutputFile()

   {

      

       if(fileChooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)

           return fileChooser.getSelectedFile();

       else

           return null;

   }

  

   private static String getUserCommand()

   {

       String[] commands = { "encrypt", "decrypt" };

  

       String command = (String) JOptionPane.showInputDialog(null, "What would you like to do?", "Commands", JOptionPane.QUESTION_MESSAGE, null, commands, commands[0]);

       return command;

      

   }

  

   private static String getPassword()

   {

         

           String password = (String) JOptionPane.showInputDialog("Password");

             

           return password;

      

   }

  

   private static void encrypt(File input, File output, String password)

   {

       try {

           BufferedInputStream bis = new BufferedInputStream(new FileInputStream(input));

           BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));

           byte b;

           int idx = 0 , len = password.length();

           while((b = (byte)bis.read()) != -1)

           {

               b += password.charAt(idx);

               if(b >= 256)

                   b -= 256;

               bos.write(b);

               idx = (idx + 1) % len; //cycle throu 0 - (len-1)

              

           }

          

           bis.close();

           bos.close();

       } catch (FileNotFoundException e) {

           System.out.println(e.getMessage());

       } catch (IOException e) {

           System.out.println("Exception occured while reading");

       }

      

   }

  

   private static void decrypt(File input, File output, String password)

   {

       try {

           BufferedInputStream bis = new BufferedInputStream(new FileInputStream(input));

           BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(output));

           byte b;

           int idx = 0 , len = password.length();

           while((b = (byte)bis.read()) != -1)

           {

               b -= password.charAt(idx);

               if(b < 256)

                   b += 256;

               bos.write(b);

               idx = (idx + 1) % len; //cycle throu 0 - (len-1)

           }

          

           bis.close();

           bos.close();

       } catch (FileNotFoundException e) {

           System.out.println(e.getMessage());

       } catch (IOException e) {

           System.out.println("Exception occured while reading");

       }

      

   }

   public static void main(String[] args) {

       JOptionPane.showMessageDialog(null, "Choose an input file");

       File inputFile = getUserInputFile();

       if(inputFile != null)

       {

           String command = getUserCommand();

           String password = getPassword();

           if(password != null)

           {

               File outputFile = getUserOutputFile();

               if(outputFile != null)

               {

                   if(command.equals("encrypt"))

                       encrypt(inputFile, outputFile, password);

                   else

                       decrypt(inputFile, outputFile, password);

                  

                   JOptionPane.showMessageDialog(null, "All Done.");

               }

           }

          

       }

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote