Copyright © infotec016 . Powered by Blogger.

Thursday, April 20, 2017

Cryptography : Railfence Cipher


Railfence Cipher


Sample java code for Railfence Cipher

Key = 3
Encryption


//key=3
import java.util.*;
public class Railfence1_encry{
    public static void main(String args[]){
        Scanner myscanner =new Scanner(System.in);
        System.out.println("Enter the plaintext");
        String word=myscanner.nextLine().replace(" ","").toLowerCase();
        System.out.println("cipher text");
int i=0;
String text1="",text3="";
while(i<word.length()){
char a=word.charAt(i);
text1=text1+a;
i=i+2;
if(i<word.length()){
a=word.charAt(i);
text3=text3+a;
}
i=i+2;
}
System.out.print(text1);
for(int j=1;j<word.length();j=j+2){
char a=word.charAt(j);
System.out.print(a);
}
System.out.println(text3);
    }
}
     

output of  the above code




Decryption


//key=3
import java.util.*;
public class Railfence1_decry{
    public static void main(String args[]){
        Scanner myscanner =new Scanner(System.in);
        System.out.println("Enter the cipher text");
        String word=myscanner.nextLine().replace(" ","");
        System.out.println("original message");
String text1="",text2="",text3="";
for(int i=0;i<word.length();i++){
if(word.length()%2==0 || ((word.length()+1)/2)%2==0){
if((word.length()/2)%2==0){
text1=word.substring(0,word.length()/4);
text2=word.substring(word.length()/4,3*word.length()/4);
text3=word.substring(3*word.length()/4,word.length());
}
else{
if(word.length()%2==1){
text1=word.substring(0,(word.length()-1)/4+1);
text2=word.substring((word.length()-1)/4+1,3*(word.length()-1)/4+1);
text3=word.substring(3*(word.length()-1)/4+1,word.length());
}
else{
text1=word.substring(0,(word.length()+2)/4);
text2=word.substring((word.length()+2)/4,(3*word.length()+2)/4);
text3=word.substring((3*word.length()+2)/4,word.length());
}
}

}
else{
text1=word.substring(0,word.length()/4+1);
text2=word.substring(word.length()/4+1,(3*word.length()/4)+1);
text3=word.substring((3*word.length()/4)+1,word.length());
}
}
String txt1="",txt2="";
for(int i=0;i<text2.length();i=i+2){
char a=text2.charAt(i);
txt1=txt1+a;
}
for(int i=1;i<text2.length();i=i+2){
char a=text2.charAt(i);
txt2=txt2+a;
}

int j=0;
while(j<word.length()){
if(j<text1.length()){
System.out.print(text1.charAt(j));
}
if(j<txt1.length()){
System.out.print(txt1.charAt(j));
}
if(j<text3.length()){
System.out.print(text3.charAt(j));
}
if(j<txt2.length()){
System.out.print(txt2.charAt(j));
}
j++;
}
    }
}




output of the above code

0 comments:

Post a Comment