Google Answers Logo
View Question
 
Q: How to encode(encrypt and decrypt) message in Java with console window ( No Answer,   7 Comments )
Question  
Subject: How to encode(encrypt and decrypt) message in Java with console window
Category: Computers > Programming
Asked by: robert4444-ga
List Price: $12.00
Posted: 17 May 2004 10:08 PDT
Expires: 19 May 2004 09:10 PDT
Question ID: 347634
simplest encoding, '111'. For instance, enter "AAABBB" in console
window, get it encrypted "BBBCCC".
Generally design a programme which could
1 read sentence (via a console window)
2 Ask wether encryption or decryption is required (via console window)
3 Decrypt/Encrypt message, including punctuation like '.' or ','.
4 together with description report, internal documentation and pseudocode.
Answer  
There is no answer at this time.

Comments  
Subject: Re: How to encode(encrypt and decrypt) message in Java with console window
From: actinoid-ga on 17 May 2004 18:51 PDT
 
Hi, This is basically what you want. You will need to tweak a little.

/*
 * Created on 18-May-2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package uk.ac.aber.csgp19.minibay.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Enumeration;
import java.util.Properties;

/**
 * @author Daniel Pettifor
 *
 * 
 *  
 */
public class EncryptDecrypter
{
	Properties crypt = null;
	Properties decrypt = null;

	/**
	 * 
	 */
	public EncryptDecrypter()
	{
		init();
	}

	public void init()
	{
		/*an easy way would be to write a config file that looked a little like this.
				a=b
				b=c
				blar blar.
				Read this in by using*/
		crypt = new Properties();
		try
		{
			crypt.load(new FileInputStream("crypt.props"));
		}
		catch (FileNotFoundException e)
		{
			System.out.println(
				"No crypt.props file. You cannot encrypt or decrype without it!");
			System.out.println(
							"Using simple test data for abc");
			crypt.put("a","b");
			crypt.put("b","c");	
			crypt.put("c","d");
			crypt.put(".",":");
			crypt.put(",",";");
		}
		catch (IOException e)
		{
		}
		/*thats the file with that info in. Just stick that in the working directory.
		you can now change your encryption to what ever you like without a recompile 
		or just hard code the properties object if you like.*/

		//Now to create a decrypt properties object
		Enumeration values = crypt.elements();
		Enumeration keys = crypt.keys();
		decrypt = new Properties();
		//now we just reverse the encrypted value with the decrypted and we
can decode easily.
		while (values.hasMoreElements() && keys.hasMoreElements())
		{ 
			String s1 = values.nextElement().toString();
			String s2 = keys.nextElement().toString();
			decrypt.put(s1,s2);
		}
	}

	public String encode(String theString, boolean encode)
	{
		/*Here you write your encrypt code.
		Just convert the string to a char array.
		Then do a for loop to go round each of the elements in the
		string array and convert it to your encrypted type for that character.
		Once you have iterated through the whole array and created your new string 
		by looking up the char in the properties object and adding the returned value 
		to a new string you have an encrypted message.*/

		//This or something similar should work.

		char[] theArray = theString.toCharArray();
		StringBuffer sbuf = new StringBuffer();
		if (encode = true)
		{

			for (int i = 0; i < theString.length(); i++)
			{
				sbuf.append(crypt.getProperty(theArray[i] + ""));
			}
		}
		else
		{
			//we know we need to decode so use the decode properties to make the message.
			for (int i = 0; i < theString.length(); i++)
			{
				sbuf.append(decrypt.getProperty(theArray[i] + ""));
			}
		}

		//	  now you return the encrypted string.
		return sbuf.toString();

	}

	public static void main(String[] args)
	{
		/*Hi,
		
			To get input from the commandline you will need to create an input
buffer to take input.*/

		EncryptDecrypter coder = new EncryptDecrypter();
		InputStreamReader menuInput = new InputStreamReader(System.in);
		BufferedReader buf = new BufferedReader(menuInput);

		/*This allowes to to get access to what you type into the console.
		
		If you want a little menu system I suggest you use a loop to build a
case based menu or what ever you like.*/

		int selection = 1;
		boolean encrypt = false;

		do
		{
			System.out.println("Type 1 to set encode/decode");
			System.out.println("Type 2 to encode/decode String");
			System.out.println("Type 0 to exit.");
			try
			{
				selection = Integer.parseInt(buf.readLine());
			}
			catch (NumberFormatException e2)
			{				
			}
			catch (IOException e2)
			{
			}
			switch (selection)
			{
				case 1 :
					System.out.println("Would you like to use encrypt? y/n");
					try
					{
						String enc = buf.readLine();
						if (enc == "y")
						{
							encrypt = true;
						}
						else
						{
							encrypt = true;
						}
						selection = 2;
						//Will get you into the next case to read in your text.
					}
					catch (Exception e)
					{
						System.out.println(
							"Didn't understand that input. Try again.");
					}

				case 2 :
					System.out.println("Enter the string.");
					String toEncrypt = null;
					try
					{
						toEncrypt = buf.readLine();
					}
					catch (IOException e1)
					{
					}
					System.out.println(
						"Result : " + coder.encode(toEncrypt, encrypt));

			}
		}
		while (selection != 0);

	}

}
Subject: yes, but
From: robert4444-ga on 18 May 2004 06:44 PDT
 
thank you mate, but basically, I need a programme which is kind of
caesar cipher encoding. For example, when running the programme,first
I can get a message asking me if I want to encrypt or decrypt..., and
after I enter any sentence in the CONSOLE WINDOW, it come out the
result by a default rule.
cheers
Subject: Re: How to encode(encrypt and decrypt) message in Java with console window
From: actinoid-ga on 18 May 2004 14:55 PDT
 
Well as I said you just need to tweak it. Change the gui so that the
first question it asks is if you want to encrypt or decrypt.
i.e. cut and paste the case 1 in front of the do while loop. Then
remove the switch and just leave a loop like you see below. A while
true. Thne it will just take input and process it each time you press
enter.

System.out.println("Would you like to use encrypt? y/n");
try
{
    String enc = buf.readLine();
    if (enc == "y") 
    {
	encrypt = true;
    }
    else
    {
	encrypt = true;
    }
}
catch (Exception e)
{
}

while(true)
{
   try
   {
       toEncrypt = buf.readLine();
   }
   catch (IOException e1)
   {
   }
   System.out.println("Result : " + coder.encode(toEncrypt, encrypt));
}
Subject: Re: How to encode(encrypt and decrypt) message in Java with console window
From: robert4444-ga on 18 May 2004 17:53 PDT
 
Thank you very much mate, however, it might be too complicated for me. 
I tried my best to write some code,as below:
public class test extends ConsoleWindow
 {
  public static void main(String[] args)
  {
  ConsoleWindow cw = new ConsoleWindow();
  char c1,c2;
  int i=0;

  cw.out.println("please input your sentence!");
  c1 = cw.input.readChar() ;
  cw.out.println("please input your code.");
  i = cw.input.readInt();

  cw.out.println("Do you want to encrypt or decrypt?") ;
  cw.out.println("Encrypt: 1");
  cw.out.println("Decrypt: 2");
  cw.out.println("Exit: 0");
  int selection;
  selection = cw.input.readInt() ;
  if (selection ==1 || selection ==2|| selection ==0)
  {
  if ( selection == 1)
  {
  c2 = (char)(c1+i);
  cw.out.println(c2);
  }
  if (selection == 2)
  {
  c2 = (char)(c1-i);
  cw.out.println(c2);
  }
  }
  else
  {
  cw.out.println("Invalid number! Please restart");
  }
}
}

but one problem I could not sort it out, 
in console window, it can only read one letter, no matter how many
words I insert, I know this is due to "c1","c2" are Char. So what
should I do to make the console window read and encode(decode) a
sentence rather than just a letter.


thank you indeed
Subject: Re: How to encode(encrypt and decrypt) message in Java with console window
From: actinoid-ga on 19 May 2004 02:56 PDT
 
Hi, Well you probably have noticed that in that code sample you are
reading only one char from the input. Hence you only get one char no
matter how many words you enter. If you could post the api or source
for the ConsoleWindow program I could probably tell you what you need
to do to make it work.

I would presume that that readChar command would return a char until
it reached the end of the buffer. Guessing I would have thought that
it would return -1 or null when this end of buffer is reached. With
this in mind you could create a loop that reads one char at a time
into a char[] of your own. Now you have all the entered text.

e.g.

char c1 = cw.input.readChar();
int index = 0;
char[] inputText new char[1024]; /*You many want to use a Vector or something
                                    so you dont get a buffer overflow.*/

while(c1 != null || c1 != -1)
{ 
    inputText[index] = c1;
    c1 = cw.input.readChar();
    
}

If you are lichy there could be a readLine() method in the
ConsoleWindow class. If there is use that as it would save you lots of
hassle.
Subject: Re: How to encode(encrypt and decrypt) message in Java with console window
From: actinoid-ga on 19 May 2004 02:59 PDT
 
Just noticed. You need to add index++; to the bottom of that loop so
you increment the index and write to a new element of the array.
Subject: Re: How to encode(encrypt and decrypt) message in Java with console window
From: robert4444-ga on 19 May 2004 09:10 PDT
 
Yes, thank you very much, it is really helpful, what a shame I have
handed my assignment already this morning, thank you indeed anyway

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy