Practical 1b(Modified Caesar Cipher)

Aim: Implementing  Substitution Cipher

  •  Modified Caesar Cipher

Theory:

In Modified Caesar Cipher the original plain text alphabets may not necessarily be three places down the line, but instead can be any places down the line.

Example : Alphabet A in the plain text would not necessarily be replaced by D. It can be replaced by any valid alphabet i.e by E or F or by G and so on. Once the replacement scheme is decided, it would be constant and will be used for all the other alphabets in that message.

Source Code:

import java.io.*;
public class caesarcipher
{
public String encrypt(int shift, String line)
{
String result=””;
int offset;
for(int i=0;i<line.length();i++)
{
offset=((int)line.charAt(i)+shift)%256;
result+=(char)(offset);
}
return result;
}
public String decrypt(int shift, String line)
{
String result=””;
int offset;
for(int i=0;i<line.length();i++)
{
offset=((int)line.charAt(i)-shift)%256;
if(offset<0)
offset+=256;
result+=(char)(offset);
}
return result;
}
public static void main(String args[])throws IOException
{
caesarcipher obj=new caesarcipher();
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
int choice;
System.out.println(“Menu:\n1: Encryption\n2: Decryption”);
choice=Integer.parseInt(in.readLine());
System.out.println(“Enter the shift: “);
int shift=Integer.parseInt(in.readLine());
System.out.println(“Enter the line: “);
String line=in.readLine();
System.out.println(“Result:”);
switch(choice)
{
case 1:System.out.println(obj.encrypt(shift,line));
break;
case 2:System.out.println(obj.decrypt(shift,line));
break;
default:
System.out.println(“Invalid input!”);
break;
}
}
}

 

Output:

 

prac1b

 


 

New innovative Ideas are always welcome. feel free to post below: