Write a program to implement Caesar Cipher encryption - decryption.

 


Code:



import java.util.Scanner;

public class CaesarCipher {

public static void main(String []args) {

Scanner sc=new Scanner(System.in);

System.out.print("1. Encryption 2. Decryption: ");
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.print("Enter plain text:");
String text = sc.next();

System.out.print("Enter Key:");
int key = sc.nextInt();

System.out.println("Encrypted text is: " + encrypted(text,key));
break;
case 2:
System.out.print("Enter Encrypted text:");
text = sc.next();

System.out.print("Enter Key:");
key = sc.nextInt();

System.out.println("Decrypted text is: "+ decrypted(text,key));
break;
default:
break;
}
}

public static StringBuffer encrypted(String text, int key)
{
StringBuffer result = new StringBuffer();

for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
char ch = (char)(((int)text.charAt(i) +
key - 65) % 26 + 65);
result.append(ch);
}
else
{
char ch = (char)(((int)text.charAt(i) +
key - 97) % 26 + 97);
result.append(ch);
}
}
return result;
}

public static StringBuffer decrypted(String text, int key)
{
StringBuffer result=new StringBuffer();

for (int i=0; i<text.length(); i++)
{
if (Character.isUpperCase(text.charAt(i)))
{
char ch = (char)(((int)text.charAt(i) - key - 65+26) % 26 + 65);
result.append(ch);
}
else
{
char ch = (char)(((int)text.charAt(i) - key - 97+26) % 26 + 97);
result.append(ch);
}
}
return result;
}
}


Output:





Comments

Popular posts from this blog

Write A Program To Print Hello World Using Lex

Create a Student registration form using following tags form,input,textarea,button,select,optio. The registration form must consist of following information: first name,Middle name,last name, gender(use radio button),address,phone no,email id,hobbies(use checkbox),city,state,country,collage name (use dropdown menu).