In: Computer Science
You are writing a program that encrypts or decrypts messages using a simple substitution cipher. Your program will use two constant strings. One will represent the code for encryption: going from the original message (called the plaintext) to the encrypted version of the message. The other will be “abcdefghijklmnopqrstuvwxyz” (the lowercase alphabet. Your program will ask the user whether they want to 1) encrypt a message, 2) decrypt a message, or 3) quit. If they choose encrypt or decrypt, you will then get the message from the user and change it to all lower case. Then you will print out the encrypted or decrypted message character by character, using the information in the code to be used for encryption or decryption. The String you will use for encryption is “csimuylangpwzfrxbvhdtejqko”.
***Java language***
/********* EncryptDecrypt.java ***********/
import java.util.Scanner;
public class EncryptDecrypt {
public static void main(String[] args) {
String mesg =
"csimuylangpwzfrxbvhdtejqko";
String encrypt = "", decrypt = "",
line;
/*
* Creating an Scanner class object
which is used to get the inputs
* entered by the user
*/
Scanner sc = new
Scanner(System.in);
int choice;
/*
* This while loop continues to
execute until the user enters a valid
* choice or 3
*/
while (true) {
// displaying
the menu
System.out.println("You may:");
System.out.println("\t1) Encrypt a message");
System.out.println("\t2) Decrypt a message");
System.out.println("\t3) Quit");
// getting
the choice entered by the user
System.out.print("Enter choice (1,2, or 3): ");
choice =
sc.nextInt();
// Based on
the user choice the corresponding case will be executed
switch (choice)
{
case 1: {
sc.nextLine();
// Getting the input entered by the user
System.out.print("Enter the message :");
line = sc.nextLine();
line = line.toLowerCase();
// Encrypting the message
for (int i = 0; i < line.length(); i++)
{
if (line.charAt(i) >= 'a'
&& line.charAt(i) <= 'z') {
int val =
(int) (line.charAt(i));
encrypt +=
mesg.charAt((val - 97));
} else {
encrypt +=
line.charAt(i);
}
}
System.out.println("Your encrypted message
is:");
System.out.println(encrypt);
continue;
}
case 2: {
sc.nextLine();
System.out.print("Enter the message :");
line = sc.nextLine();
String lowerline = line.toLowerCase();
// Decrypting the message
for (int i = 0; i < lowerline.length(); i++)
{
if (lowerline.charAt(i) >=
'a'
&& lowerline.charAt(i) <= 'z')
{
for (int j
= 0; j < mesg.length(); j++) {
if (mesg.charAt(j) == lowerline.charAt(i))
{
if
(Character.isUpperCase(line.charAt(i)))
decrypt +=
(char) (65 + j);
else
decrypt +=
(char) (97 + j);
break;
}
}
} else {
decrypt +=
line.charAt(i);
}
}
System.out.println("Your decrypted message is:
");
System.out.println(decrypt);
continue;
}
case 3: {
break;
}
default:
{
continue;
}
}
break;
}
}
}
/**********************************************/
/**********************************************/
Output:
/**********************************************/