2 Replies - 1107 Views - Last Post: 02 December 2013 - 04:18 AM Rate Topic: -----

#1 jayburn00  Icon User is offline

  • D.I.C Head

Reputation: 1
  • View blog
  • Posts: 151
  • Joined: 05-July 12

Java transposition encryption program not working

Posted 01 December 2013 - 11:32 PM

I am working on a program that will encrypt and decrypt messages using transposition cyphers and believe I have finished the component that does encryption (and displays the content). However, when i try to compile, I get a lot of errors, but all of them the same two error types: "Incorrect type" (or something along those lines) or "Inconvertible type" (Or again, something along those lines. Here is the code I have created, with large segments commented out to reduce the number of errors, since they are all the same error. Any advice on how to fix it would be appreciated:

import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.text.*;

public class tcgui2 extends JFrame {
   // Transposition Cipher GUI or tcgui2
   private Container contents;
   private JTextField textin, keyin;
   private JRadioButton encryptbtn, decryptbtn;
   private ButtonGroup radiobtngroup; 
   private JLabel inlabel, keylabel, ctoutlbl, ctout;
   private JButton cancelbutton, clearbutton, computebutton;
   //how to get these variables and others like them to work?
   string key;
   string messagePreEnc;

   public tcgui2 () 
   {
      super("tcgui2");
	  contents = getContentPane();
	  contents.setLayout( new FlowLayout() );

	  encryptbtn = new JRadioButton( "Encryption",true );
	  decryptbtn = new JRadioButton( "Decryption" );
 
	  inlabel = new JLabel("Enter Plain Text: ");
	  textin = new JTextField(40); 
	  keylabel = new JLabel("Enter key (4-15 char): ");
	  keyin = new JTextField(15); 
	  ctoutlbl = new JLabel("Encrypted Text: ");
	  ctout = new JLabel("");
	  //Instance variable
	  
	  
	  
	  // instantiate buttons
	  cancelbutton = new JButton("Cancel");
	  clearbutton = new JButton("Clear");
	  computebutton = new JButton("Compute");
	  
	  // add components to the window
	  contents.add( encryptbtn );
	  contents.add( decryptbtn );
	  
	  // create radio button group
	  radiobtngroup = new ButtonGroup( );
	  radiobtngroup.add( encryptbtn );
	  radiobtngroup.add( decryptbtn );
	  
	  contents.add( inlabel );
	  contents.add( textin ); // Plain text or cipher text entry field
	  contents.add( keylabel );
	  contents.add( keyin );  // Keyword entry
	  contents.add( ctoutlbl );
	  contents.add( ctout ); // Encrypted text is displayed through this label
	  
	  contents.add(cancelbutton);
	  contents.add(clearbutton);
	  contents.add(computebutton);
	  
	  cancelbutton.addActionListener( new ActionListener()
        {
            public void actionPerformed (ActionEvent e)
            {
				//String s = "Exiting...";
				//JOptionPane.showMessageDialog(null,s);
                System.exit(0);
            }
        });

		clearbutton.addActionListener( new ActionListener()
        {
            public void actionPerformed (ActionEvent e)
            {
				textin.setText ("");
				keyin.setText ("");
				ctout.setText ("");
            }
        });
		
	    computebutton.addActionListener( new ActionListener()
        {
            public void actionPerformed (ActionEvent e)
            {
				// TODO ... replace  the following with appropriate method calls
				if (encryptbtn.isSelected()) { //encryption radio button is selected
				   ctout.setText(textin.getText());
				   System.out.println("Given Plain Text is being Encrypted.");
				   }
				else  if (decryptbtn.isSelected()) { //decryption radio button is selected
				   ctout.setText(textin.getText());
				   System.out.println("Given Cipher Text is being Decrypted.");
				   }
            }
        });

	  setSize(475, 350);
	  setVisible(true);
	}
	
	public boolean getKey()
	{
		key = keyin.getText();
		/*if(!keyCheck())
		{
			return false;
		}*/
		
		return true;
	}
	
	/*private boolean keyCheck()
	{
		key = key.toUpperCase();
		//check key contents present
		if (key.length() == 0)
		{
			textin.setText("Key is empty!");
			return false;
		}
		
		//check for spaces
		for (int i=0; i < key.length(); i++)
		{
			if (key.charAt(i) == ' ')
			{
				textin.setText("Spaces are in key!");
				return false;
			}
		}
		
		//check length
		if (key.length() < 4)
		{
			textin.setText("Key is shorter than 4 characters!");
			return false;
		}
		
		//check for duplicate letters
		for (int i=0; i<key.length() - 1; i++)
		{
			for (int c = i+1; c < key.length(); c++)
			{
				if (key.charAt(i) == key.charAt(c))
				{
					textin.setText("Duplicate letters in key!");
					return false;
				}
			}
		}
		
		return true;
	}*/
	
	//Get message to encrypt
	public boolean getPreEnc()
	{
		string messagePreEnc = textin.getText();
		/*if (!checkPreEnc())
		{
			return false;
		}
		removePreEncSpaces();*/
		return true;
	}
	
	//check message to encrypt
	/*private boolean checkPreEnc()
	{
		if (messagePreEnc.length() == 0)
		{
			textin.setText("Message box is empty!");
			return false;
		}
		
		return true;
	}*/
	
	//Remove spaces make caps
	/*private void removePreEncSpaces()
	{
		messagePreEnc=messagePreEnc.toUpperCase();
		StringBuffer temp=new StringBuffer();
		
		for (int i=0; i<messagePreEnc.length(); i++)
		{
			if (!(messagePreEnc.charAt(i)== ' '))
			{
				temp.append(messagePreEnc.charAt(i));
			}
		}
		
		messagePreEnc = temp.toString();
	}*/
	
	public void encryptMessage()
	{
		//Check if extra chars needed.
		int moreChars = key.length() - (messagePreEnc.length() % key.length());
		
		//add neccesary chars.
		if (!(moreChars == key.length()))
		{
			for (int i=0; i<moreChars; i++)
			{
				messagePreEnc += "Z";//I would use a non letter character that wouldn't be used often, like ~, since the letter z might be a part of the message.
			}
		}
		String temp[] = new String[key.length()];
		
		int k = 0;
		int j = 0;
		for (int i =0; i< key.length(); i++)
		{
			temp[i] = key.substring(i, i+1);
			j = k;
			for (; j < messagePreEnc.length(); j+= key.length())
			{
				temp[i] += messagePreEnc.substring(j, j+1);
			}
			++k;
		}
		
		int matched = 0;
		
		//not exactly sure how this part works, but got it from research on similar programs.
		for (int i = 65; i<=90; i++)
		{
			for (j=0; j<key.length(); j++)
			{
				if ((char)i == temp[j].charAt(0))
				{
					ctout += temp[j].substring(1);
					++matched;
				}
			}
			if (matched >= key.length())
			{
				break;
			}
		}
	}
	
  
   public static void main (String [] args) {
      tcgui2 cy = new tcgui2();
	  cy.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
	  }
}



Is This A Good Question/Topic? 0
  • +

Replies To: Java transposition encryption program not working

#2 x68zeppelin80x  Icon User is offline

  • D.I.C Addict

Reputation: 130
  • View blog
  • Posts: 576
  • Joined: 07-March 09

Re: Java transposition encryption program not working

Posted 02 December 2013 - 03:58 AM

First and foremost,

View Postjayburn00, on 02 December 2013 - 02:32 AM, said:

string key;
string messagePreEnc;


Should be:
String key;
String messagePreEnc;


String is capitalized.

As for the part you don't understand:

View Postjayburn00, on 02 December 2013 - 02:32 AM, said:

//not exactly sure how this part works, but got it from research on similar programs.
for (int i = 65; i<=90; i++)
{
	for (j=0; j<key.length(); j++)
	{
		if ((char)i == temp[j].charAt(0))
		{
			ctout += temp[j].substring(1);
			++matched;
		}
	}
	if (matched >= key.length())
	{
		break;
	}
}



Well, the outer loop is looping over the ASCII character A-Z. The second loop is indexing each of positions in your key. The if conditional is checking if the current letter in the outer loop matches the first letter in your temp String. If it does, you are append a string value to a JLabel which is illegal.

You need to do:
ctout.setText(ctout.getText() + temp[j].substring(1));


After you have appended the text to the JLabel, you are incrementing the match counter. After the inner loop is finished, you check if the number of matches exceeds or is equal to the length of your key String. If it is, you break the outer loop (which again, is looping through the ASCII decimal representations of the letters A-Z).

Check out the ASCII table for additional insight.

I highly advise you use an array of characters vs a string, when performing encryption. Not only is it easier to manipulate the character array, as the String is immutable, but you cannot deallocate a String. In other words, you cannot change the String once, you are done with it. It is just floating around in Java land...

This post has been edited by x68zeppelin80x: 02 December 2013 - 04:02 AM

Was This Post Helpful? 1
  • +
  • -

#3 x68zeppelin80x  Icon User is offline

  • D.I.C Addict

Reputation: 130
  • View blog
  • Posts: 576
  • Joined: 07-March 09

Re: Java transposition encryption program not working

Posted 02 December 2013 - 04:18 AM

To help you better understand, you can change the outer loop to loop over actual characters:

for (int i = 'A'; i <= 'Z'; i++) {
	for (j = 0; j < key.length(); j++) {
		if ((char) i == temp[j].charAt(0)) {
			ctout.setText(ctout.getText() + temp[j].substring(1));
			++matched;
		}
	}
	if (matched >= key.length()) {
		break;
	}
}

This post has been edited by x68zeppelin80x: 02 December 2013 - 05:37 AM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1