Write a program that performs text encryption and decryption on a certain input
ID: 3719977 • Letter: W
Question
Write a program that performs text encryption and decryption on a certain input string.
First, ask the user to input a string. Then, ask the user for an encryption parameter, between 1 and 30.
Write a separate Class named “EncryptionHelper”. This class has a static function called “Encrypt”. This function accepts a String parameter, and an integer parameter.
The Encrypt function iterates over each character of the input string that is passed to it. It converts each character to it's corresponding integer value in the ASCII table, and then subtracts the given encryption parameter from that number. Finally, the resulting number is converted back to a char and the sequence of characters is put together to create the encrypted string.
The class Encryption Helper should also provide a function called “Decrypt”. This function also accepts a string and an integer parameter, and reverses the process, to create clear text out of an encrypted string.
Explanation / Answer
//Code to copy
//EncryptionHelper.java
import java.util.Scanner;
public class EncryptionHelper
{
public static void main(String[] args) {
//Create an instance of Scanner class
Scanner scanner=new Scanner(System.in);
System.out.println("Enter plain text :");
String plaintext=scanner.nextLine();
System.out.println("Enter shift(1-30):");
int shift=Integer.parseInt(scanner.nextLine());
//call Encrypt method
String encryptedMsg=EncryptionHelper.Encrypt(plaintext, shift);
System.out.println("Encrypted Message : "+
encryptedMsg);
//call Decrypt method
System.out.println("Decrypted Message : "+
EncryptionHelper.Decrypt(encryptedMsg, shift));
}
/*
* The method Encrypt that takes string message and shift,d
* and then returns the encrypted message.
* */
public static String Encrypt(String msg,int d)
{
StringBuffer sb=new StringBuffer();
for (int i = 0; i < msg.length(); i++) {
char c=(char)(msg.charAt(i)+d);
if(c>'z')
c=(char) ('a'+d-('z'-msg.charAt(i)+1));
sb.append(c);
}
return sb.toString();
}
/*
* The method Decrypt that takes string message and shift,d
* and then returns the encrypted message.
* */
public static String Decrypt(String msg,int d)
{
StringBuffer sb=new StringBuffer();
for (int i = 0; i < msg.length(); i++) {
char c=(char)(msg.charAt(i)-d);
if(c>'z')
c=(char) ('a'+d-('z'-msg.charAt(i)+1));
sb.append(c);
}
return sb.toString();
}
}//end of the class
--------------------------------------------------------------------
Sample Output:
Enter plain text :
hello world
Enter shift(1-30):
1
Encrypted Message : ifmmp!xpsme
Decrypted Message : hello world
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.