Java program to Implement Rail Fence Cipher

Ram Pothuraju
// 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;ic;i++)
  {
   for(int j=0;jr;j++)
   {
    if(k!=len)
     mat[j][i]=plainText.charAt(k++);
    else
     mat[j][i]='X';
   }
  }
  for(int i=0;ir;i++)
  {
   for(int j=0;jc;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;ir;i++)
  {
   for(int j=0;jc;j++)
   {
    mat[i][j]=cipherText.charAt(k++);
   }
  }
  for(int i=0;ic;i++)
  {
   for(int j=0;jr;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(cipherTextdepth);
                
  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

Post a Comment

7Comments

  1. Thanks Dude it works Successfully in java as well as in android thank you for sharing

    ReplyDelete
  2. hi, 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?

    ReplyDelete
  3. Hai, Rail Fence cipher was suppose to be "zig zag" right ? why does it arrange it descending order only??

    ReplyDelete
Post a Comment