Complete the classes cipher - caesar and transpose

Assignment Help JAVA Programming
Reference no: EM13839662

Cryptography, the study of secret writing, has been around for a very long time, from simplistic techniques to sophisticated mathematical techniques. No matter what the form however, there are some underlying things that must be done - encrypt the message and decrypt the encoded message.

One of the earliest and simplest methods ever used to encrypt and decrypt messages is called the Caesar cipher method, used by Julius Caesar during the Gallic war. According to this method, letters of the alphabet are shifted by three, wrapping around at the end of the alphabet. For example,

PlainTest: a b c d e f g h i j k l m n o p q r s t u v w x y z
Caesar shift: d e f g h I j k l m n o p q r s t u v w x y z a b c

When encrypting a message, you take each lette r of the message and replace it with its corresponding letter from the shifted alphabet. To decrypt an encoded message, you simply reverse the operation. That is, you take the letter from the shifted alphabet and replace it with the corresponding letter from the plaintext alphabet. Thus the string the quick brown fox becomes wkh txlfn eurzq ira

Another type of cipher is known as Transposition cipher. In this type of cipher, letters in the original message are re-arranged in some methodical way - for instance, reverse the letters in each string. Thus the string the quick brown fox becomes eht kciuq nworb xof

Still yet another cipher method is the Reverser cipher. This method does not only reverses the letters in each word, but as does the Transposition cipher, but it also reverses the result generated from the Transposition cipher. Hence the original message the quick brown fox becomes xof nworb kciuq eht

Class design

Here are three Crypt ography methods - Caesar, Transposition and Reverser. They all have something in common. They encrypt and decrypt messages. That is, they take a string of words and translate each word using the encoding algorithm appropriate for that cipher. Thus each class cipher will need polymorphic encode() and decode() methods, which take a word and encodes and decodes it according to the rule of the particular cipher.

From a design perspective, the encrypt() method and the decrypt() methods will be the same for every class. They simply break message into words and have each word encode or decode. However, the encode and decode methods will be different for each cipher.

From the above analysis a partial abstract class Cipher is depicted be by Listing 1.

import java.uti l.StringTokenizer;

public abstract class Cipher
{
private String message; // The message string
StringBuffer encrypted_message,
decrypted_message;

public Cipher(String text)
{
// Complete definition
}

public final void encrypt()
{
/* The message string is tokenized into individual words, and each word is encoded
by calling the encode method
*/
encrypted_message = new StringBuffer("");
StringTokenizer words = new StringTokenizer(message);

while(words.hasMoreTokens())
{
String s = words.nextToken();
s = encode(s) + " ";
encrypted_message.append(s);
}
}

public final void decrypt(String message)
{
/* The encoded message string is tokenized into individual words, and each word is
encoded by calling the decode method
*/

decrypted_message = new StringBuffer("");
StringTokenizer words = new StringTok enizer(message);

while(words.hasMoreTokens())
{
String s = words.nextToken();
s = decode(s) + " ";
decrypted_message.append(s);
}
}

String getEncodedMessage()
{
return encrypted_message.toString();
}

String getDecodedMessage()
{
return decrypted_message.toString();
}

public abstract String encode(String s);
public abstract String decode(String s);
}

Listing 1. Abstract class Cipher

The class Caesar inherits the abstract class Cipher. This class defines the methods code and decode. The method encode takes a String parameter and returns a String result. It takes each character of the parameter and performs a Caesar shift on the character. That is, a shift with possible wrap around can be coded as follows:
char ch = word.charAt(i);
ch = (char)('a' + ch - 'a' + 3) % 26);

The method decode does the reverse. Listing 2 shows a partial definition of this class - Caesar

public class Caeser extends Cipher
{
public Caeser(String s)
{
super(s);
}
public String encode(String word)
{
StringBuffer result = new StringBuffer();

for (int i = 0; i < word.length(); i++)
{
char ch = word.charAt(i);
ch = determineCharacter(ch, Constants. ENCODE_SHIFT);
result.append(ch);
}
return result.toString();
}

public String decode(String word)
{
// Complete the method and return the decoded word
}

public char determineCharacter(char ch, int shift)
{
if(Character.isLowerCase(ch))
ch = (char)(''a'' + (ch - ''a'' + shift) % Constants.WRAP_AROUND);
return ch;
}
}

Listing 2.

In similar fashion, the class Transpose inherits Cipher and defines the methods code and encode. Listing 3 shows an incomplete definition of the class Transpose.

public class Transpose extends Cipher
{
Transpose(String s)
{
super(s);
}
public String encode(String word)
{
//Complete the method and return the encoded word
}
public String decode(String word)
{
// Complete the method and return the decoded word
}
}
Listing 3

The class Reverser inherits the class Transpose. Listing 4 shows an incomplete definition of this class.

public class Reverser extends Transpose
{
Reverser(String s)
{
super(s);
}

String reverseText(String word)
{
// Complete the method and returns the reverse transposed version;
}
}

Listing 4

Things to do
From the above discussion

. Complete the classes Cipher, Caesar, and Transpose, and Reverser. In addition
. Define an interface called Constants that will store the value 26 in the identifier WRAP_AROUND; similarly, store 3 in the identifier, ENCODE_SHIFT, and 23 in the identifier DECODE_SHIFT (needed to decode the encoded message). The code in the method determineCharacter(char ch, int shift) accounts for lower case letters only. Extend the code to include both upper and lower case letters.

Listing 5 Use the following test class to implement your other classes.

import javax.swing.JOptionPane;

class TestEncryption
{
public static void main(String arg[])
{
String code, output = "";

String text = JOptionPane.showInputDialog("Enter message");

output += "The original message is \n" + text + "\n";

Cipher c = new Caeser(text);
c.encrypt();
code = c.getEncodedMessage();
output += "\nCeasar Cipher\nThe encrypted message is \n" + code + "\n";
c.decrypt(code);
code = c.getDecodedMessage();
output +="The decrypted message is \n" + code + "\n";

c = new Transpose(text);
c.encrypt( );
code = c.getEncodedMessage();
output += "\nTranspose\nThe encrypted Transpose message is \n" + code + "\n";
c.decrypt(code);
code = c.getDecodedMessage();
output +="The decripted Transpose message is \n" + code + "\n";

Reverser r = new Reverser(text);
r.encrypt();
code = r.reverse( r.getEncodedMessage() );
output += "\nReverser\nThe encrypted Reverse message is \n" + code+ "\n";
code = r.decode(code);
output+="The decrypted Reverse message is \n" + code;

System.out.println(output);
}
}

Reference no: EM13839662

Questions Cloud

Find the mean or median and mode : Find the mean or median and mode
Write a cover letter for an advertised job : SOLICITED LETTER: Write a cover letter for an advertised job, or a job about which you have specific knowledge (perhaps a new opening at your current place of employment)
Write a paper on health care organization profile : In the role of a Health Care Manager. Write a paper address "Health Care Organization Profile", should include the following components, Name and type of health care organization (stand-alone, multifacility, multicampus, community-based, etc.).
Will we ever go beyond the milky way : Will we ever go beyond The Milky Way to explore other galaxies?
Complete the classes cipher - caesar and transpose : Complete the classes Cipher, Caesar, and Transpose, and Reverser - Define an interface called Constants that will store the value 26 in the identifier WRAP_AROUND;
Selma will develop for inclusion in the mmh website : Summarize your findings from Items #1 and #2Recommend design features that you and Selma will develop for inclusion in the MMH websiteUse APA format for any quotations or citations you use to support your answers
Determine the resulting charge on each capacitor : Determine the resulting charge on each capacitor.
How much energy can this capacitor store without breaking : How much energy can this capacitor store without breaking down
How would you provide alternative policy options : Then assess the role of public opinion in relation to the Affordable Care Act. Is there a difference between public opinion and lobbyist portrayal of public opinion? How would you provide alternative policy options

Reviews

Write a Review

JAVA Programming Questions & Answers

  Write following java expressions in mathematical notation

Write the following Java expressions in mathematical notation.

  Developing a java application

You have been requested to develop a Java application for the local library as part of an upgrade initiative. As in all libraries, this is a place where one can check out books

  Implementing a relatively simple text-compression scheme

You will be implementing a relatively simple text-compression scheme - It should run from the command line.

  Accepts a binary number from the user

Write a Java test program that accepts a binary number from the user. You should store the binary number in a String. Your program should then use afor loop to sequence through every character in the String, counting the number of ones, zeros, and..

  You need to prepare a java program using class

You need to prepare a java program using class and method to calculate commission of sales person with fix salary of $75,000 and 25% sales commission. Program should prompt for amount of total sales

  Create a program called date java to perform

Create a program called Date.java to perform error-checking on the initial values, for instance: fields month, day, and year. Also, provide a method nextDay() to increment the day by one. The Date object should always remain in a consistent state.

  Writing a program that computes the average salary

The first programming project involves writing a program that computes the average salary for a collection of employees of different types. This program consists of four classes

  Write a program that asks for purchase price

Write a program that asks for purchase price and to calculate, state sales tax, county sales tax and then display purchase price, both sales tax amount and then the total.

  A game of tic-tac-toe

A game of tic-tac-toe, two players (one the computer) take turns marking an available cell in a 3 X 3 grid (a two dimensional array) with their respective tokens (either and X or an O). When one player has placed three tokens in a horizontal

  Java test program

Write a Java test program, all your code should be in the main method, that determines what type of organization is indicated by a web address. Your program should allow the user to enter a web address

  Balancing binary search trees

Balancing Binary Search Trees,  Consider the file BST.java (a link to this file is provided below for downloading purposes) which defines a generic Binary Search Tree class.

  Need the build function.use recursion

Implement remaining function. Everything else is provided. Use given material to receive points. Implement remaining function. Everything else is provided. Use given material to receive points. Implement remaining function. Everything else is provide..

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd