// File Name: RailFence.java
import java.util.*;
class RailFenceBasic{
int depth;
String Encryption(String plainText,int depth)throws Exception
{
int r=depth,len=plainText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String cipherText="";
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
if(k!=len)
mat[j][i]=plainText.charAt(k++);
else
mat[j][i]='X';
}
}
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
cipherText+=mat[i][j];
}
}
return cipherText;
}
String Decryption(String cipherText,int depth)throws Exception
{
int r=depth,len=cipherText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String plainText="";
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
mat[i][j]=cipherText.charAt(k++);
}
}
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
plainText+=mat[j][i];
}
}
return plainText;
}
}
class RailFence{
public static void main(String args[])throws Exception
{
RailFenceBasic rf=new RailFenceBasic();
Scanner scn=new Scanner(System.in);
int depth;
String plainText,cipherText,decryptedText;
System.out.println("Enter plain text:");
plainText=scn.nextLine();
System.out.println("Enter depth for Encryption:");
depth=scn.nextInt();
cipherText=rf.Encryption(plainText,depth);
System.out.println("Encrypted text is:\n"+cipherText);
decryptedText=rf.Decryption(cipherText, depth);
System.out.println("Decrypted text is:\n"+decryptedText);
}
}
OUTPUT
Enter plain text:
railfencecipher
Enter depth for Encryption:
3
Encrypted text is:
rlnchafcieieepr
Decrypted text is:
railfencecipher
NOt working
ReplyDeletecan't run
ReplyDeleteThanks Dude it works Successfully in java as well as in android thank you for sharing
ReplyDeletewlcm bro
ReplyDeleteits working bro
ReplyDeletehi, how would add an offset to this so that the user can input the starting row for the plain text to be added into the array?
ReplyDeleteHai, Rail Fence cipher was suppose to be "zig zag" right ? why does it arrange it descending order only??
ReplyDelete