You are on page 1of 4

Name: Shaikh Danish Irfan

Roll No.: 3859


Class: TYIT-C
2. Modify Caesar Cipher
import java.util.Scanner;
public class ModifyCaesarCipher
{
final int total_alphabets=26;
String encrypted="",decrypted="";
char ch;
public String encrypt(String plain,int key)
{
for(int i=0;i<plain.length();i++)
{
ch=plain.charAt(i);
if(ch==' ')
{
encrypted+="_";
}
else if(ch>='A'&&ch<='Z')
{
if(ch<='Z'-key)
encrypted+=String.valueOf((char)(ch+key));
else
encrypted+=String.valueOf((char)(ch-(total_alphabets-key)));
}
else

Name: Shaikh Danish Irfan


Roll No.: 3859
Class: TYIT-C
encrypted+=String.valueOf(ch);
}
return encrypted;
}
public String decrypt(String cipher,int key)
{
for(int i=0;i<cipher.length();i++)
{
ch=cipher.charAt(i);
if(ch==' ')
{
decrypted+="_";
}
else if(ch>='A'&&ch<='Z')
{
if(ch>='A'+key)
decrypted+=String.valueOf((char)(ch-key));
else
decrypted+=String.valueOf((char)(ch+(total_alphabets-key)));
}
else
decrypted+=String.valueOf(ch);
}
return decrypted;

Name: Shaikh Danish Irfan


Roll No.: 3859
Class: TYIT-C
}
public static void main(String[] args)
{
String plaintext,ciphertext;
int key;
ModifyCaesarCipher cc=new ModifyCaesarCipher();
System.out.print("Enter text: ");
plaintext=new Scanner(System.in).nextLine().toUpperCase();
System.out.print("Enter key: ");
key=new Scanner(System.in).nextInt();
ciphertext=cc.encrypt(plaintext,key);
System.out.println("Encrypted text: "+ciphertext);
plaintext=cc.decrypt(ciphertext,key);
System.out.println("Decypted text: "+plaintext);
}
}
Output:

Name: Shaikh Danish Irfan


Roll No.: 3859
Class: TYIT-C

You might also like