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 letter 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 Cryptography 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. Figure 1
shows a hierarchy of the classes.
Cipher
Transpose Caesar
Reverser
Figure 1. Inheritance hierarchy
From the above analysis a partial abstract class Cipher is
depicted be by Listing 1.
import java.util.StringTokenizer;
public abstract class Cipher { private String message; StringBuffer
encrypted_message, decrypted_message;
public Cipher(String text) { // Complete the constructor 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 */
// Supply the code that will decrypt the encrypted string
}
public String getEncodedMessage() { return
encrypted_message.toString(); }
public 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) { return
code(word,Constants.ENCODE_SHIFT ); }
public String decode(String word) { // Complete this method so that
it decodes the encoded string } String code(String word, int SHIFT)
{ StringBuffer result = new StringBuffer();
for (int i = 0; i < word.length(); i++) { char ch =
word.charAt(i); ch = determineCharacter(ch, SHIFT);
result.append(ch); } return result.toString(); } public char
determineCharacter(char ch, final int shift) {
if(Character.isUpperCase(ch)) ch = (char)('A' + (ch - 'A' + shift)
% Constants.WRAP_AROUND); // Complete the if/else so that lower
case letters are accounted for 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) { StringBuffer result = new
StringBuffer(word); result.reverse(); return result.toString(); }
public String decode(String word) { // Complete this method so that
it reverses the encoded string; } }
Listing 3
The class Reverser inherits the class Transpose. Listing 4 shows an
incomplete definition of this class.
public class Reverser extends Transpose { public Reverser(String s)
{ // Complete the constructor }
public String reverseText(String word) { // Complete this method so
that it reverses the original string }
public String decode(String word) { // Complete this method so that
it reverses the reversed string }
}
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 shows a typical implementation of the algorithms.
import javax.swing.JOptionPane;
public 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";
c = new Reverser(text); c.encrypt(); code = c.getEncodedMessage();
code =c.reverseText(code); output += "\nReverser\nThe encrypted
Reverse message is \n" + code+ "\n"; code = c.decode(code);
output+="The decrypted Reverse message is \n" + code;
display(output); } static void display(String s) {
JOptionPane.showMessageDialog(null, s, "Encrypt/decrypt",
JOptionPane.INFORMATION_MESSAGE); } }
Listing 5.
Listing 5 has errors as shown, you must find these errors and fix
them, in order for the program to compile. This is the only section
that has problems, therefore do not alter any other parts of the
code.
Answer:-
The below is the required source code for the given problem in JAVA
Code:-
TestEncryption.java:
import javax.swing.JOptionPane;
public class TestEncryption {
public static void main(String arg[])
{
//Try to
get the information from the user.
try {
String code, output = "";
String text = JOptionPane.showInputDialog("Enter
message");
//Check that the user did not leave the field empty.
if (!text.isEmpty()) {
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.getEncodedMessage();
code = r.reverseText(code);
output += "\nReverser\nThe encrypted Reverse message is \n" + code
+ "\n";
code = r.decode(code);
output += "The decrypted Reverse message is \n" + code;
display(output);
} else {
JOptionPane.showMessageDialog(null, "Invalid message entered.",
"Encrypt/decrypt",
JOptionPane.ERROR_MESSAGE);
}
} catch
(NullPointerException e) {
JOptionPane.showMessageDialog(null, "Program terminated",
"Encrypt/decrypt",
JOptionPane.INFORMATION_MESSAGE);
}
}
/**
* Displays the information.
*/
static void display(String s) {
JOptionPane.showMessageDialog(null, s, "Encrypt/decrypt",
JOptionPane.INFORMATION_MESSAGE);
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Transpose.java
public class Transpose extends Cipher {
/**
* Constructor.
*/
Transpose(String s) {
super(s);
}
/**
* Encodes the word.
*/
@Override
public String encode(String word) {
StringBuffer result =
new StringBuffer(word);
result.reverse();
return
result.toString();
}
/**
* Decodes the word.
*/
@Override
public String decode(String word) {
// Complete this method
so that it reverses the encoded string;
return
encode(word);
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Reverser.java:
public class Reverser extends Transpose {
/**
* Constructor.
*/
public Reverser(String s) {
super(s);
}
/**
* Reverses the text.
*/
public String reverseText(String word) {
// Complete this method
so that it reverses the original string
Reverser i = new
Reverser(word);
i.encrypt();
StringBuilder code = new
StringBuilder(i.getEncodedMessage());
return
code.reverse().toString();
}
/**
* Decodes the message.
*/
@Override
public String decode(String word) {
// Complete this method
so that it reverses the reversed string
return
super.decode(word);
}
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Constants.java:
public interface Constants {
/**
* The amount of letter to wrap around when
the end of alphabet has reached.
*/
public static final int WRAP_AROUND =
26;
/**
* The amount of letter to shift the
alphabet to encode.
*/
public static final int ENCODE_SHIFT =
3;
/**
* The amount of letter to shift the
alphabet to decode.
*/
public static final int DECODE_SHIFT =
23;
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Cipher.java:
import java.util.StringTokenizer;
public abstract class Cipher {
private String message;
StringBuffer encrypted_message,
decrypted_message;
/**
* Constructor
*/
public Cipher(String message) {
this.message =
message;
}
/**
* Encrypts the message.
*/
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);
}
}
/**
* Decrypts the message.
*/
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 StringTokenizer(message);
while
(words.hasMoreTokens()) {
String s = words.nextToken();
s = decode(s) + " ";
decrypted_message.append(s);
}
}
/**
* Gets the encoded message.
*/
public String getEncodedMessage() {
return
encrypted_message.toString();
}
/**
* Gets the decoded
message.
*/
public String getDecodedMessage() {
return
decrypted_message.toString();
}
/**
* Abstract encode
*/
public abstract String encode(String
s);
/**
* Abstract decode
*/
public abstract String decode(String s);
}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Cipher.java:
public class Caeser extends Cipher {
/**
* Constructor for the
class.
*/
public Caeser(String s) {
super(s);
}
/**
* Encodes the message.
*/
@Override
public String encode(String word) {
return code(word,
Constants.ENCODE_SHIFT);
}
/**
* Decodes the message.
*/
@Override
public String decode(String word) {
return code(word,
Constants.DECODE_SHIFT);
}
/**
* Encodes or decodes.
*/
String code(String word, int SHIFT) {
StringBuffer result =
new StringBuffer();
for (int i = 0; i <
word.length(); i++) {
char ch = word.charAt(i);
ch = determineCharacter(ch, SHIFT);
result.append(ch);
}
return
result.toString();
}
/**
* Determines what character should be
returned after the shift.
*/
public char determineCharacter(char ch, final
int shift) {
if
(Character.isUpperCase(ch)) {
ch = (char) ('A' + (ch - 'A' + shift) %
Constants.WRAP_AROUND);
} else if
(Character.isLowerCase(ch)) {
ch = (char) ('a' + (ch - 'a' + shift) %
Constants.WRAP_AROUND);
}
return
ch;
}
}
If you find any
difficulty with the code, please let know know I will try for any
modification in the code. Hope this answer will helps you. If you
have even any small doubt, please let me know by comments. I am
there to help you. Please give Thumbs Up,Thank You!! All the
best
Cryptography, the study of secret writing, has been around for a very long time, from simplistic...
Can someone please help me for this assignment? Cryptography — the science of secret writing — is an old science; the first recorded use was well before 1900 B.C. An Egyptian writer used previously unknown hieroglyphs in an inscription. We will use a simple substitution cypher called rot13 to encode and decode our secret messages. ROT13 ("rotate by 13 places", sometimes hyphenated ROT-13) is a simple letter substitution cipher that replaces a letter with the 13th letter after it, in...
Caesar Cipher v3 Decription Description A Caesar cipher is one of the first and most simple encryption methods. It works by shifting all letters in the original message (plaintext) by a certain fixed amount (the amounts represents the encryption key). The resulting encoded text is called ciphertext. Example Key (Shift): 3 Plaintext: Abc Ciphertext: Def Task Your goal is to implement a Caesar cipher program that receives the key and an encrypted paragraph (with uppercase and lowercase letters, punctuations, and...
Change the following Shift Cipher program so that it uses OOP(constructor, ect.) import java.util.*; import java.lang.*; /** * * @author STEP */ public class ShiftCipher { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Scanner input = new Scanner(System.in); String plainText; System.out.print("Please enter your string: "); // get message plainText = input.nextLine(); System.out.print("Please enter your shift cipher key: "); // get s int s = input.nextInt(); int...
You will be writing a simple Java program that implements an ancient form of encryption known as a substitution cipher or a Caesar cipher (after Julius Caesar, who reportedly used it to send messages to his armies) or a shift cipher. In a Caesar cipher, the letters in a message are replaced by the letters of a "shifted" alphabet. So for example if we had a shift of 3 we might have the following replacements: Original alphabet: A B C...
In java write a command-line program that helps to decrypt a message that has been encrypted using a Caesar cipher1. Using this method, a string may contain letters, numbers, and other ASCII characters, but only the letters (upper- and lower-case) are encrypted – a constant number, the shift, is added to the ASCII value of each letter and when letters are shifted beyond ‘z’ or ‘Z’ they are wrapped around (e.g. “Crazy?” becomes “Etcba?” when shifted by 2). When your...
JAVA public static String generatePassword(String gp) { String password=""; boolean b= false; for (int i =0;i { char ch = gp.charAt(i); if (i == 0) { password += Character.toUpperCase(ch); } if (ch == 'S' || ch == 's') ...
For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...
JAVA Problem: With the recent news about data breaches and different organizations having their clients’ information being exposed, it is becoming more and more important to find ways to protect our sensitive data. In this program we will develop a simple tool that helps users generate strong passwords, encrypt and decrypt data using some cyphering techniques. You will need to create two classes. The first class is your driver for the application and contains the main method. Name this class...
In C++ Having heard you have gotten really good at programming, your friend has come to ask for your help with a simple task. She would like you to implement a program to encrypt the messages she exchanges with her friends. The idea is very simple. Every letter of the alphabet will be substituted with some other letter according to a given key pattern like the one below. "abcdefghijklmnopqrstuvwxyz" "doxrhvauspntbcmqlfgwijezky" // key pattern For example, every 'a' will become a...
This is my assignment prompt This is an example of the input and output This is what I have so far What is the 3rd ToDo in the main.cpp for open the files and read the encrypted message? Does the rest of the code look accurate? Programming Assignment #6 Help Me Find The Secret Message Description: This assignment will require that you read in an encrypted message from a file, decode the message, and then output the message to a...