Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a Java program that will cryptographically encode and decode a message. T

ID: 3544079 • Letter: C

Question

Create a Java program that will cryptographically encode and decode a message. The program will first ask a user to enter the secret "key," which it will use to encrypt the messages that are typed in next. The key will be needed to decrypt the messages. The message and its encryption will be in lower-case characters.

Your program will use a simple substitution cypher, that is, each letter that is typed in will be substituted by the appropriate letter in the key. A space will not be encrypted, so it will remain a space.

Your program will have a character array named 'key' that will store the 26 letters of the English alphabet plus a space character in random order. For example, the key might be

Using the above key, the program would operate as follows:

In the main method,

Explanation / Answer

public static void main(String[] args) throws IOException
{
char[] key = new char[26];
System.out.println("Enter the key as a random ordering of the 26 letters of the English alphabet");
for(int i=0; i < 26; i++)
{
System.out.print((i+1)+":");
char tmp = (char) new InputStreamReader(System.in).read();
boolean contains = false;
int ascii = tmp;
if(ascii < 65 || (ascii>122) || ((ascii<97 && ascii>90 )))
{
System.out.println("Please enter "+(i+1)+" again");
i--;
continue;
}
if(ascii < 97)
{
ascii = ascii + 32;
}
for(int j = 0; j < 26; j++)
{
if(key[j] == tmp)
{
contains = true;
break;
}
}
if(!contains)
{
key[i] = tmp;
}
else
{
System.out.println("Please enter "+(i+1)+" again");
i--;
continue;
}
}
boolean askInput = true;
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

while(askInput)
{
System.out.print("Enter the message to be encrypted: ");
String message = br.readLine();
if(message.equalsIgnoreCase(""))
{
break;
}
char[] msgChar = message.toCharArray();
char[] encrypted = encrypt(key,msgChar,message.length());
String encryptedMessage = "";
for(int i = 0; i < encrypted.length; i++)
{
encryptedMessage += encrypted[i];
}
System.out.println("The encrypted message is:"+encryptedMessage);
}
System.out.println("Goodbye!");
}
private static char[] encrypt(char[] key,char[] msgChar,int length)
{
char[] encrypted = new char[length];
for(int j = 0; j < msgChar.length; j++)
{
int ascii = msgChar[j];
if(ascii < 65 || (ascii>122) || ((ascii<97 && ascii>90 )))
{
encrypted[j] = msgChar[j];
continue;
}
if(ascii > 90)
{
ascii = ascii - 32;
}
ascii = ascii - 'A';
encrypted[j] = key[ascii];
}
return encrypted;
}