Welcome to HBH! If you had an account on hellboundhacker.org you will need to reset your password using the Lost Password system before you will be able to login.

Caesar Cipher - Java Code Bank


Caesar Cipher
My first program on my own, feedback wanted. The program asks the user for a string, then asks for a number by which to shift the characters. It encodes/decodes the string and prints both forms.
                /**
 * @author Greg_G
 *
 */

	import javax.swing.*;

	
	
	public class Ceasar1 {

	
		private String plaintext;

		private static int keyOffset;



	public Ceasar1()

	{

		plaintext = null;

		keyOffset = 0;

	}



	public static void main(String [] args)

	{

		Ceasar1 cipherArray = new Ceasar1();

		String tmp = cipherArray.encrypt();

		System.out.println("This is after encryption:" + tmp );
	
		System.out.println(decrypt("This is decrypted back to its original form" + tmp ) );

		System.exit(0);

	}



	public String encrypt()

	{

		plaintext = ((String)JOptionPane.showInputDialog("enter string to encrypt:") ).toLowerCase().trim();

		keyOffset = Integer.parseInt(JOptionPane.showInputDialog("enter offset to shift the letters by:") );



		String alphabet = "abcdefghijklmnopqrstuvwxyz";



		StringBuffer sbuff = new StringBuffer();

		int holder = plaintext.length();



		for(int i = 0; i < holder; i++)

	{

			String tmp = ""+plaintext.charAt(i);


			int offset = alphabet.indexOf(tmp);
			

			offset += keyOffset;



			if( offset > 25 )

	{

				int newOffset = 0;

				newOffset = offset % 25;

				sbuff.append(alphabet.charAt(newOffset) );

	}



			else

	{

				sbuff.append(alphabet.charAt(offset));

	}


	}

		return sbuff.toString();

	

	}
	
	public static String decrypt(String tmp) {
		
		String alphabetdec = "abcdefghijklmnopqrstuvwxyz";


		StringBuffer sbuff = new StringBuffer();

	
		int holder = tmp.length();


		for(int i = 0; i < holder; i++)

		{
			
			String tmp1 = ""+tmp.charAt(i);	

			int offset = alphabetdec.indexOf(tmp1);



			offset -= keyOffset;
	
			if( offset < 0 )

		{

				int newOffset = 0;

				newOffset = offset + 25;

				sbuff.append( alphabetdec.charAt(newOffset) );

		}


			else

		{

				sbuff.append( alphabetdec.charAt(offset) );

		}


		}
		
		
		return sbuff.toString();


	}

	
}

            
Comments
Sorry but there are no comments to display