Rail Fence Cipher – Encryption and
Decryption
Given a plain-text message and a numeric key, cipher/de-cipher the given text using Rail Fence
algorithm.
The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives
its name from the way in which it is encoded.
ENCRYPTION
In a transposition cipher, the order of the alphabets is re-arranged to obtain the cipher-text.
• In the rail fence cipher, the plain-text is written downwards and diagonally on
successive rails of an imaginary fence.
• When we reach the bottom rail, we traverse upwards moving diagonally, after reaching
the top rail, the direction is changed again. Thus the alphabets of the message are written
in a zig-zag manner.
• After each alphabet has been written, the individual rows are combined to obtain the
cipher-text.
For example, if the message is “GeeksforGeeks” and the number of rails = 3 then cipher is prepared
as:
DECRYPTION
As we’ve seen earlier, the number of columns in rail fence cipher remains equal to the length
of plain-text message. And the key corresponds to the number of rails.
• Hence, rail matrix can be constructed accordingly. Once we’ve got the matrix we can
figure-out the spots where texts should be placed (using the same way of moving
diagonally up and down alternatively ).
1
• Then, we fill the cipher-text row wise. After filling it, we traverse the matrix in zig-zag
manner to obtain the original text.
Implementation:
Let cipher-text = “GsGsekfrek eoe” , and Key = 3
• Number of columns in matrix = len(cipher-text) = 12
• Number of rows = key = 3
Hence original matrix will be of 3*12 , now marking places with text as ‘*’ we get
* _ _ _ * _ _ _ * _ _ _ *
_ * _ * _ * _ * _ * _ *
_ _ * _ _ _ * _ _ _ * _
2
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="";
3
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 Rail{
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);
}
}
4
OUTPUT
5
Hill Cipher
Hill cipher is a polygraphic substitution cipher based on linear algebra. Each letter is
represented by a number modulo 26. Often the simple scheme A = 0, B = 1, …, Z = 25 is used,
but this is not an essential feature of the cipher. To encrypt a message, each block of n letters
(considered as an n-component vector) is multiplied by an invertible n × n matrix, against
modulus 26. To decrypt the message, each block is multiplied by the inverse of the matrix used
for encryption.
The matrix used for encryption is the cipher key, and it should be chosen randomly from the
set of invertible n × n matrices (modulo 26).
Examples:
Input : Plaintext: ACT
Key: GYBNQKURP
Output : Ciphertext: POH
Input : Plaintext: GFG
Key: HILLMAGIC
Output : Ciphertext: SWK
ENCRYPTION
We have to encrypt the message ‘ACT’ (n=3).The key is ‘GYBNQKURP’ which can be written as the nxn
matrix:
The message ‘ACT’ is written as vector:
6
The enciphered vector is given as:
which corresponds to ciphertext of ‘POH’
DECRYPTION
To decrypt the message, we turn the ciphertext back into a vector, then simply multiply by the inverse
matrix of the key matrix (IFKVIVVMI in letters).The inverse of the matrix used in the previous example
is:
For the previous Ciphertext ‘POH’:
which gives us back ‘ACT’.
Assume that all the alphabets are in upper case.
Below is the implementation of the above idea for n=3.
7
CODE
// Java code to implement Hill Cipher
class GFG
{
// Following function generates the
// key matrix for the key string
static void getKeyMatrix(String key, int keyMatrix[][])
{
int k = 0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
keyMatrix[i][j] = (key.charAt(k)) % 65;
k++;
}
}
}
// Following function encrypts the message
static void encrypt(int cipherMatrix[][],
int keyMatrix[][],
int messageVector[][])
{
int x, i, j;
for (i = 0; i < 3; i++)
{
for (j = 0; j < 1; j++)
{
cipherMatrix[i][j] = 0;
for (x = 0; x < 3; x++)
{
cipherMatrix[i][j] +=
keyMatrix[i][x] * messageVector[x][j];
}
cipherMatrix[i][j] = cipherMatrix[i][j] % 26;
}
}
}
// Function to implement Hill Cipher
static void HillCipher(String message, String key)
{
// Get key matrix from the key string
int [][]keyMatrix = new int[3][3];
getKeyMatrix(key, keyMatrix);
int [][]messageVector = new int[3][1];
// Generate vector for the message
for (int i = 0; i < 3; i++)
messageVector[i][0] = (message.charAt(i)) % 65;
int [][]cipherMatrix = new int[3][1];
// Following function generates
8
// the encrypted vector
encrypt(cipherMatrix, keyMatrix, messageVector);
String CipherText="";
// Generate the encrypted text from
// the encrypted vector
for (int i = 0; i < 3; i++)
CipherText += (char)(cipherMatrix[i][0] + 65);
// Finally print the ciphertext
System.out.print(" Ciphertext:" + CipherText);
}
// Driver code
public static void main(String[] args)
{
// Get the message to be encrypted
String message = "ACT";
// Get the key
String key = "GYBNQKURP";
HillCipher(message, key);
}
}
9
OUTPUT
10