100% found this document useful (1 vote)
1K views

Rail Fence Cipher Program in Python Language

The Rail Fence Cipher is a simple transposition cipher that rearranges the letters of a plaintext message in a zigzag pattern using a predetermined number of "rails". To encrypt, the message is written out row by row down the rails and then read off column by column. Decryption involves writing the ciphertext out in the same zigzag pattern in a matrix and then reordering the letters in the matrix to recover the original plaintext message. The document provides examples of encryption and decryption, outlines the algorithms, and includes Python code to implement the Rail Fence Cipher.

Uploaded by

batch22ubit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
1K views

Rail Fence Cipher Program in Python Language

The Rail Fence Cipher is a simple transposition cipher that rearranges the letters of a plaintext message in a zigzag pattern using a predetermined number of "rails". To encrypt, the message is written out row by row down the rails and then read off column by column. Decryption involves writing the ciphertext out in the same zigzag pattern in a matrix and then reordering the letters in the matrix to recover the original plaintext message. The document provides examples of encryption and decryption, outlines the algorithms, and includes Python code to implement the Rail Fence Cipher.

Uploaded by

batch22ubit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

Rail Fence Cipher

Introduction
The Rail Fence Cipher is a simple transposition cipher that involves writing the plaintext in a zigzag
pattern across a number of "rails," and then reading off the ciphertext by row. The cipher is named after
its resemblance to a zig-zag fence.
For example, let’s consider the plaintext “This is a secret message”.

To encode this message we will first write over two lines (the “the rails of the fence”) as follows:

Note that all white spaces have been removed from the plain text:
The ciphertext is then read off by writing the top row first, followed by the bottom row:

Algorithm:
The Rail Fence Cipher is a transposition cipher that rearranges the plaintext letters by writing them in a
zigzag pattern. Here's the algorithm for the Rail Fence Cipher:
Encryption Algorithm:
● Input: Plain text message and the number of rails (num_rails).
● Remove white spaces and special characters from the plaintext message.
● Create an empty matrix with num_rails rows and the length of the cleaned plaintext message
columns, initialized with dots ('.').
● Iterate through the matrix in a zigzag pattern and place each character of the message in the
appropriate position in the matrix.
● Concatenate the characters row-wise to get the encrypted text.
Decryption Algorithm:
● Input: Cipher text message and the number of rails (num_rails).
● Remove white spaces and special characters from the cipher text message.
● Create an empty matrix with num_rails rows and the length of the cleaned cipher text message
columns, initialized with dots ('.').
● Fill the matrix in a zigzag pattern with the characters of the cipher text.
● Reorder the matrix to reconstruct the original order of characters.
● Read the characters row-wise to obtain the decrypted text.

Implementation of Rail Fence Cipher:


import re
# Encryption Function
def cipher_encryption():
msg = input("Enter the message to encrypt: ")
rails = int(input("Enter the number of rails for encryption: "))
# Removing white space from message
msg = msg.replace(" ", "")
# Creating an empty matrix
railMatrix = [['.' for _ in range(len(msg))] for _ in range(rails)]
# Putting letters of message one by one in the matrix in zig-zag
row, check = 0, 0
for i in range(len(msg)):
if check == 0:
railMatrix[row][i] = msg[i]
row += 1
if row == rails:
check = 1
row -= 1
elif check == 1:
row -= 1
railMatrix[row][i] = msg[i]
if row == 0:
check = 0
row = 1
encryp_text = "".join("".join(row) for row in railMatrix)
encryp_text = re.sub(r"\.", "", encryp_text)
print("Encrypted Text: {}".format(encryp_text))

# Decryption Function
def cipher_decryption():
msg = input("Enter the message to decrypt: ")
rails = int(input("Enter the number of rails for decryption: "))
# Removing white space from message
msg = msg.replace(" ", "")
# Creating an empty matrix
railMatrix = [['.' for _ in range(len(msg))] for _ in range(rails)]
# Putting letters of message one by one in the matrix in zig-zag
row, check = 0, 0
for i in range(len(msg)):
if check == 0:
railMatrix[row][i] = msg[i]
row += 1
if row == rails:
check = 1
row -= 1
elif check == 1:
row -= 1
railMatrix[row][i] = msg[i]
if row == 0:
check = 0
row = 1
# Reordering the matrix
ordr = 0
for i in range(rails):
for j in range(len(msg)):
temp = railMatrix[i][j]
if re.search("\\.", temp):
continue
else:
railMatrix[i][j] = msg[ordr]
ordr += 1
# Putting reordered matrix into decrypted text string to get decrypted text
check, row = 0, 0
decryp_text = ""
for i in range(len(msg)):
if check == 0:
decryp_text += railMatrix[row][i]
row += 1
if row == rails:
check = 1
row -= 1
elif check == 1:
row -= 1
decryp_text += railMatrix[row][i]
if row == 0:
check = 0
row = 1
decryp_text = re.sub(r"\.", "", decryp_text)
print("Decrypted Text: {}".format(decryp_text))

# Calling Inputs in Main Function


def main():
print("Rail Fence Cipher")
while True:
print("Menu:")
print("1. Encryption")
print("2. Decryption")
print("3. Exit")
choice = input("Choose an option (1, 2, 3): ")
if choice == '1':
print("---Encryption---")
cipher_encryption()
elif choice == '2':
print("---Decryption---")
cipher_decryption()
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid Choice. Please enter a valid option.")

if __name__ == "__main__":
main()

You might also like