Solved

Vignere Cipher

Posted on 2003-11-02
6
894 Views
Last Modified: 2008-02-26
Hello All,

I am struggling to write a Vignere cipher program using Java code, just like the one on this website:  http://www.sharkysoft.com/misc/vigenere/
Here are the requirements:

The vignere encoder/decoder uses a plain text message as input and produces  a plain text encrypted/decrypted message.  
The plain text will be uppercase alphabetic characters and whitespace.
The whitespace characters will delimit words in the message but will not be encrypted/decrypted.  One or more whitespace characters must appear between words in the encrypted/decrypted message.
The user provides the appropriate encryption key and the file name.
the program must process the text input from the file and display the encrypted/decrypted message in a GUI.
The user may choose to save the resulting message to a file.  Here is the skeleton that I was provided in order to complete this cipher:


public class Cipher {

/**
  * Reads in the file, and if there are any IO exceptions returns the error.  
  * Otherwise,returns a String that is the encrypted version of the file.
  *
  *@param fileName the name of the file to be encrypted
  *@param key the key to use for encryption, which will be all upper case.
  *@return the encoded version of the file
  */
  public String encryptFile(String file, String key) {  }


 /**
  * Reads in the file, and if there are any IO exceptions returns the error.
  * Otherwise,returns a String that is the decrypted version of the file.
  *
  *@param fileName the name of the file to be decrypted
  *@param key the key to use for decryption, which will be all upper case.
  *@return the decoded version of the file
  */
 
  public String decryptFile(String file, String key){  }


/**
 * Shifts the given character by the given number.
 * @param c character to be shifted
 * @param amtToShift amount to shift the characer
 * @return the resulting character after shift
 */
private char shiftIt(char c, int amtToshift) {  }

/**
 * Returns how far the current character needs to be shifted based on the key.
 *
 * @return the amount the current character needs to be shifted based on the key.
 */
private int shiftDistance() {   }

}

Can anyone help me!!!

Nicole
0
Comment
Question by:loni1023
  • 2
  • 2
6 Comments
 
LVL 15

Accepted Solution

by:
jimmack earned 190 total points
ID: 9667512
Well, we can't do your assignment for you, but here are some steps that should help to guide you in the right direction (you should be able to see how you are progressing and hopefully, you'll be able to fill in the details as you go along).

1) Create the basic GUI (a JFrame containing a BorderLayout JPanel should do)
1.1) In the North area, add the text field (JTextField) in which you can enter the key string.
1.2) In the Center area, add a text area (JTextArea) in which you will display the output
1.3) In the South area, add another JPanel, using a FlowLayout, containing the encrypt and decrypt buttons (JButton)

2) When you are happy with the GUI, implement the encryptFile() method in your Ciper class skeleton to simply read a file (don't worry about encryption yet).  Call this method from your GUI (from the ActionListener added to the encrypt button).  Make sure the file is displayed in the text area.

3) Implement the shiftIt() method in the Cipher skeleton to shift the provided character by 1 letter.

4) Call the shiftIt() method for each character in the string you have read from the file in the encryptFile() method.  Ensure the message has been correctly shifted when it is displayed in the GUI.

5) Add a counter to the encryptFile() method to cycle through the key string.  Modify the shiftIt() method appropriately.

When you've got that far, you should be able to finish it without too much help ;-)
0
 

Author Comment

by:loni1023
ID: 9673583
Thanks, jimmack for the guidance on the Vignere Cipher
0
 

Author Comment

by:loni1023
ID: 9673666
Jimmack...Here is my code so far..but I am still a little confused....I am very new to this

The Cipher Classimport java.io.*;
  //import java.crypto.*;
  //import javax.crypto.Cipher;
  //import javax.crypto.KeyGenerator;

 
 
 
  public class Cipher {
 
   /**
     * Reads in the file, and if there are any IO exceptions returns the error.  
     * Otherwise,returns a String that is the encrypted version of the file.
     *
     *@param fileName the name of the file to be encrypted
     *@param key the key to use for encryption, which will be all upper case.
     *@return the encoded version of the file
     */
  public String encryptFile(String file, String key) {  
      
      
      try {
      
            BufferedReader br = new BufferedReader (new FileReader ((file)));
            String inputLine = null;
                  int aFile = 0;
            String s;
      
            while((inputLine=br.readLine())!= null){
            for (int bFile=0; bFile !>= inputLine; bFile++
            )
            
            s=br.ReadLine;
            String =
            for (>s.length(); charAt()
            
            charAt();
            
            
            /**Reads until the end of the file*/
                         // = Integer.parseInt(s);/**Converts string to int*/
                         System.out.println (s);
                  s =br.ReadLine;
            
                  }
      }catch (IOException e) {
      System.err.println("Input File Error: "+ e);
      }
 
      }  
        
        

   /**
     * Reads in the file, and if there are any IO exceptions returns the error.
     * Otherwise,returns a String that is the decrypted version of the file.
     *
     *@param fileName the name of the file to be decrypted
     *@param key the key to use for decryption, which will be all upper case.
     *@return the decoded version of the file
     */
                                 
  public String decryptFile(String file, String key){  }

      try{
      
            BufferedReader br= new BufferedReader (newFilereader((file)));
            String inputLine= null;
            
            int aFile = 0;
            String s;
      
            while((inputLine=br.readLine())!= null){
            for (int bFile=0; bFile !>= inputLine; bFile++
            )
            
            
            charAt();
 /**
    * Shifts the given character by the given number.
    * @param c character to be shifted
    * @param amtToShift amount to shift the characer
    * @return the resulting character after shift
    */
  private char shiftIt(char c, int amtToshift) {  

   /**
     * Returns how far the current character needs to be shifted based on the key.
     *
     * @return the amount the current character needs to be shifted based on the key.
     *

         ArrayList spaces = newArrayList();
       String stripped ="";
       //strips out everything but letters and spaces
      
       for (int i = 0; i<file.length(); i++)
      
             {
            
         char c= .charAt(i);
        if(Characater.isLetter(c) || c =='')
           stripped +=c;
     
      /**String is made into uppercase*
     stripped = stripped.toUpperCase();
     
     /**position of the spaces is saved*
     int ind = 0;
     while((ind= stripped.indexOf("",ind))> -1)
     spaces.add(new Integer(ind));
     
     /**spaces removed*
     stipped.replaceAll("","");
     String encoded = vignere(stripped);
     
     int amtToshift
     try {
     
     FileReader fr = new FileReader ();
     FileWriter wtr = new FileWriter (
     */
      c =   (char)  ((c + amtToshift) ) ;
       if (c > 'Z') {
       c =   (char) (c - 26);
       }
       return c;
  }
   private int shiftDistance() {  
     }

public static void main (String[] args) {}
      

 }



And here is my GUI:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;


/**
 * This is the the view portion of the program which is what
 * the user sees and interacts with.  This is the display for
 * filename input/output, key input, encrypt/decrypt choices,and the save
 * file choice.
 *@author Lonnda Williams (lnwillia@unity.ncsu.edu)
 */

public class CipherGUI extends JFrame implements ActionListener {
     
     
/**
 * Label that displays "Enter Input Filename:" to indicate which text
 *field to input the filename
 */
 private JLabel lblFile = new JLabel ("Enter Input Filename: ");

/**
 * Text field in which the file is inputted
 *
 */
 private JTextField txtFile = new JTextField ("",15);

/**
 * Label that displays "Enter Key:" to indicate which text
 *field to input the key in
 */
 private JLabel lblKey - new JLabel ("Enter Key: ");
 
 /**
 * Text field in which the file is inputted
 *
 */
 private JTextField txtKey = new JTextField ("",15);
 
 /**
 *Button that displays "Encrypt" which allows the user to click
 *so that the file can be encrypted
 */
 private JButton btnEncrypt = new JButton ("Encrypt");
 
 /**
 * Button that displays "Decrypt" which allows the user to click so
 *so that the file can be decrypted
 */
 private JButton btnDecrypt = new JButton ("Decrypt");
 
 /**
 * Text Area shows the file with the encrypted/decrypted message
 */
 private JTextArea ta = new JTextArea (30,30);

/**
 *Label displays "Enter Output Filename:" to indicate which text
 *field to enter output file
 */
 private JLabel lblOutput = new JLabel ("Enter Output Filename: ");
 
 /**
 *Text field in which the file is inputted
 *
 */
 private JTextField txtOutput = new JLabel ("",10);
 
 /**
 *Button that when clicked it saves the file that user wants
 *
 */
 private JButton btnSave = new JButton ("Save");
 
 
 
 /**Constructor creates the GUI for Cipher.
  *@param myCipher the model for the Cipher
  */
  public CipherGUI(Cipher myCipher) {
 
        newCipher = myCipher;
      
      setTitle ("Vignere Cipher");
      setLocation (100,100);
      setSize(200,200);
      
      Container c = getContentPane();
      c.setBackground(Color.white);
      c.setForeground(Color.black);
      c.setLayout(new BorderLayout());
      /** Adds labels, buttons, and text
       *
       */
      
      c.add(lblFile, BorderLayout.NORTH);      
      c.add(txtFile, BorderLayout.NORTH);
      c.add(lblKey, BorderLayout.NORTH);
      c.add(txtKey, BorderLayout.NORTH);
      c.add(btnEncrypt, BorderLayout.NORTH);
      c.add(btnDecrypt, BorderLayout.North);
      c.add(txtta, BorderLayout.CENTER);
      c.add(lblOutput, BorderLayout.SOUTH);
      c.add(txtOutput,BorderLayout.SOUTH);
      c.add(btnSave,BorderLayout.SOUTH);
      
      btnEncrypt.addActionListener(this);
      btnDecrypt.addActionListener(this);
      btnSave.addActionListener(this);
      setDefaultCloseOperation(EXIT_ON_CLOSE);
      setVisible(true);


I don't really understand what is going on from here....thanx for helping again in advance...if it's too much, I understand

N.
0
 
LVL 15

Expert Comment

by:jimmack
ID: 9674838
I can't really do much more on the encryption/decryption front, but here is your code with the syntax errors fixed and the formatting improved to make it more readable ;-)

I've changed the layout of the GUI (I hope it is satisfactory).

I've also implemented the ActionListener method "actionPerformed" in your GUI class so that it displays some text in the text area (just so you can see how to do it).

As I said before, get the encrypt working before you start working on the decrypt.

Here you are:

Cipher.java
---------------
import java.io.*;

public class Cipher
{

    /**
     * Reads in the file, and if there are any IO exceptions returns the error.
     * Otherwise,returns a String that is the encrypted version of the file.
     *
     * @param  key       the key to use for encryption, which will be all upper case.
     * @param  file      Description of the Parameter
     * @return           the encoded version of the file
     */
    public String encryptFile(String file, String key)
    {
        StringBuffer resultBuffer = new StringBuffer();

        try
        {

            BufferedReader br = new BufferedReader(new FileReader((file)));
            String inputLine = null;
            int aFile = 0;
            char c;

            while ((inputLine = br.readLine()) != null)
            {
                for (int bFile = 0; bFile < inputLine.length(); bFile++)
                {
                    c = inputLine.charAt(bFile);
                    c = shiftIt(c, shiftDistance());
                    resultBuffer.append(c);
                }
            }
        }
        catch (IOException e)
        {
            System.err.println("Input File Error: " + e);
        }

        return (resultBuffer.toString());
    }



    /**
     * Reads in the file, and if there are any IO exceptions returns the error.
     * Otherwise,returns a String that is the decrypted version of the file.
     *
     * @param  key       the key to use for decryption, which will be all upper case.
     * @param  file      Description of the Parameter
     * @return           the decoded version of the file
     */

    public String decryptFile(String file, String key)
    {
        return ("Not implemented yet");
    }


    /**
     * Shifts the given character by the given number.
     *
     * @param  c           character to be shifted
     * @param  amtToshift  Description of the Parameter
     * @return             the resulting character after shift
     */
    private char shiftIt(char c, int amtToshift)
    {
        char result = (char)0;

        // If the character is not a space work out what it will be after it is shifted.
        if (c != ' ')
        {
            result = c;
        }

        return (result);
    }


    /**
     * Returns how far the current character needs to be shifted based on the key.
     *
     * @return    the amount the current character needs to be shifted based on the key.
     */

    /*
     *  ArrayList spaces = newArrayList();
     *  String stripped ="";
     *  /strips out everything but letters and spaces
     *  for (int i = 0; i<file.length(); i++)
     *  {
     *  char c= .charAt(i);
     *  if(Characater.isLetter(c) || c =='')
     *  stripped +=c;
     */
    /**
     *String is made into uppercase
     *
     * @return    Description of the Return Value
     */
//     stripped = stripped.toUpperCase();

    /**
     *position of the spaces is saved
     *
     * @return    Description of the Return Value
     */
//     int ind = 0;
//     while((ind= stripped.indexOf("",ind))> -1)
//     spaces.add(new Integer(ind));

    /**
     *spaces removed
     *
     * @return    Description of the Return Value
     */
//     stipped.replaceAll("","");
//     String encoded = vignere(stripped);

//     int amtToshift
//     try {

//     FileReader fr = new FileReader ();
//     FileWriter wtr = new FileWriter (
//      c =   (char)  ((c + amtToshift) ) ;
//       if (c > 'Z') {
//       c =   (char) (c - 26);
//       }
//       return c;
//  }

    private int shiftDistance()
    {
        return (0);
    }
}


CipherGUI.java
--------------------
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 * This is the the view portion of the program which is what
 * the user sees and interacts with.  This is the display for
 * filename input/output, key input, encrypt/decrypt choices,and the save
 * file choice.
 *
 * @author     Lonnda Williams (lnwillia@unity.ncsu.edu)
 * @created    03 November 2003
 */

public class CipherGUI extends JFrame implements ActionListener
{

    /**
     * Label that displays "Enter Input Filename:" to indicate which text
     *field to input the filename
     */
    private JLabel lblFile = new JLabel("Enter Input Filename: ");

    /**
     * Text field in which the file is inputted
     */
    private JTextField txtFile = new JTextField("", 15);

    /**
     * Label that displays "Enter Key:" to indicate which text
     *field to input the key in
     */
    private JLabel lblKey = new JLabel("Enter Key: ");

    /**
     * Text field in which the file is inputted
     */
    private JTextField txtKey = new JTextField("", 15);

    /**
     *Button that displays "Encrypt" which allows the user to click
     *so that the file can be encrypted
     */
    private JButton btnEncrypt = new JButton("Encrypt");

    /**
     * Button that displays "Decrypt" which allows the user to click so
     *so that the file can be decrypted
     */
    private JButton btnDecrypt = new JButton("Decrypt");

    /**
     * Text Area shows the file with the encrypted/decrypted message
     */
    private JTextArea ta = new JTextArea(30, 30);

    /**
     *Label displays "Enter Output Filename:" to indicate which text
     *field to enter output file
     */
    private JLabel lblOutput = new JLabel("Enter Output Filename: ");

    /**
     *Text field in which the file is inputted
     */
    private JTextField txtOutput = new JTextField("", 10);

    /**
     *Button that when clicked it saves the file that user wants
     */
    private JButton btnSave = new JButton("Save");

    private Cipher myCipher;


    /**
     *Constructor creates the GUI for Cipher.
     *
     */
    public CipherGUI()
    {
        myCipher = new Cipher();

        setTitle("Vignere Cipher");
        setLocation(100, 100);
        setSize(600, 200);

        Container c = getContentPane();
        c.setBackground(Color.white);
        c.setForeground(Color.black);
        c.setLayout(new BorderLayout());

        JPanel northPanel = new JPanel(new FlowLayout());
        northPanel.add(lblFile);
        northPanel.add(txtFile);
        northPanel.add(lblKey);
        northPanel.add(txtKey);
        c.add(northPanel, BorderLayout.NORTH);
       
        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(btnEncrypt);
        buttonPanel.add(btnDecrypt);
        c.add(buttonPanel, BorderLayout.SOUTH);
        c.add(ta, BorderLayout.CENTER);

/*
        c.add(lblOutput, BorderLayout.SOUTH);
        c.add(txtOutput, BorderLayout.SOUTH);
        c.add(btnSave, BorderLayout.SOUTH);
*/

        btnEncrypt.addActionListener(this);
        btnDecrypt.addActionListener(this);
        btnSave.addActionListener(this);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setVisible(true);
    }
   
    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == btnEncrypt)
        {
            ta.append("Encrypt pressed\n");
        }
        else if (e.getSource() == btnDecrypt)
        {
            ta.append("Decrypt pressed\n");
        }
    }
   
    public static void main(String[] args)
    {
        new CipherGUI();
    }
}
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Suggested Solutions

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
This video teaches viewers about errors in exception handling.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now