IMPLEMENTATION OF CAESER CIPHER

AIM:
To implement the substitution concept of Caesar Cipher using Java

ALGORITHM:
Step 1: Input the Plain text value and Key value.
Step 2: Validate the input.
Step 3: Encrypt the Plain text using the key.
Step 4: Decrypt the encrypted text

PROGRAM:
import java.util.Scanner;
public class CeaserCipher {
public static void main(String[] str)
{
String alphabets = "abcdefghijklmnopqrstuvwxyz";
Scanner sc = new Scanner(System.in);
System.out.println("Pleasse enter the text to be encrypted ");
String text = sc.next();
text = text.toLowerCase();
System.out.println("Please enter the key ");
int key = sc.nextInt();
sc.close();
if(key <=0 || key >= alphabets.length() )
{
System.out.println("Invalid Key");
return;
}
//encryption
String encryptedText = "";
for(int i=0; i < text.length(); i++)
{
char currChar = text.charAt(i);
int charPosition = alphabets.indexOf(currChar);
int newCharPosition = 0;
if(charPosition == -1) {
System.out.println(" Invalid character " + currChar);
return;
}
else if((charPosition + key) >= alphabets.length())
{
newCharPosition = charPosition + key - alphabets.length() ;
}
else
{
newCharPosition = charPosition + key;
}
encryptedText = encryptedText + alphabets.charAt(newCharPosition);
}
System.out.println("Encrypted Text: "+ encryptedText);
//decryption
String decryptText = "";
for(int i=0; i < encryptedText.length(); i++)
{
char currChar = encryptedText.charAt(i);
int charPosition = alphabets.indexOf(currChar);
int newCharPosition = 0;
if((charPosition - key) < 0) {
newCharPosition = alphabets.length() + ( charPosition - key );
} else {
newCharPosition = charPosition - key;
}
decryptText = decryptText + alphabets.charAt(newCharPosition);
}
System.out.println("Decripted Text: "+ decryptText);
}
}
Output
Pleasse enter the text to be encrypted
computer
Please enter the key
5
Encrypted Text: htruzyjw
Decripted Text: computer