Copyright © infotec016 . Powered by Blogger.

Thursday, April 20, 2017

Cryptography : Caesar Cipher


Caesar Cipher

Sample java code for Caesar Cipher

key : each letter shift of two in alphabet order
caesar cipher encryption

eg: hello -----------jgnnq
encryption


import java.util.*;
public class encryption{
public static void main(String args[]){
Scanner myScanner=new Scanner(System.in);
String alpha="abcdefghijklmnopqrstuvwxyz";
String word,text="";
System.out.println("Enter the plain text");
word=myScanner.nextLine().toLowerCase();
System.out.println("cipher text");
for(int i=0;i<word.length();i++){
boolean found=false;
char a=word.charAt(i);
int j=0;
while(j<alpha.length() && !found ){
char b=alpha.charAt(j);
if(a==' '){
text=text+" ";
found=true;
}
else if(a==b ){
found=true;
if(j<24){
text=text+alpha.substring(j+2,j+3);
}
else{
text=text+alpha.substring(j-alpha.length()+2,j-alpha.length()+3);
}
}
j++;
}
}
System.out.print(text);
}
}

output of the above code
   
caesar cipher decryption
key : each letter shift of two in alphabet order

eg: jgnnq-----------hello

decryption
import java.util.*;
public class decryption{
public static void main(String args[]){
Scanner myScanner=new Scanner(System.in);
String alpha="abcdefghijklmnopqrstuvwxyz";
String word,text="";
System.out.println("Enter the cipher text");
word=myScanner.nextLine().toLowerCase();
  System.out.println("Original text");
for(int i=0;i<word.length();i++){
boolean found=false;
char a=word.charAt(i);
int j=0;
while(j<alpha.length() && !found ){
char b=alpha.charAt(j);
if(a==' '){
text=text+" ";
found=true;
}
else if(a==b ){
found=true;
if(j>1){
text=text+alpha.substring(j-2,j-1);
}
else{
text=text+alpha.substring(alpha.length()-2+j,alpha.length()-1+j);
}
}
j++;
}
}
System.out.print(text);
}
}         

output of the above code



                                                                                                                                             

0 comments:

Post a Comment