Zig Zag Message Encryption

Zig Zag Message Encryption

Write a Python program to encrypt a message with the rail-fence method. The program will ask the user to input the message to hide and print out the encoded output,

This method consists of writing the text as a zig-zag with a given height and extract the ciphertext which is the concatenation of the 3 “words” created after applying the method. For this Python coding project, use a height of 3 lines.
For example, if the message input by the user is “helloworld”, the zig zag must produce:

h   o    l
 e l w r d
  l   o

And the the ciphertext will be “holelwrdlo”

Source code


def rail_fence_cipher(text, num_rails):
    # Create a matrix to store the zigzag pattern
    matrix = [['' for _ in range(len(text))] for _ in range(num_rails)]
    
    # Initialize direction and row
    down = False
    row = 0
    
    # Fill the zigzag matrix
    for i in range(len(text)):
        matrix[row][i] = text[i]
        if (row == 0) or (row == num_rails - 1):
            down = not down
        row += 1 if down else -1
    
    # Extract the characters from the matrix
    result = []
    for i in range(num_rails):
        for j in range(len(text)):
            if matrix[i][j] != '':
                result.append(matrix[i][j])
    return "".join(result)

# Test the function
text = input("Enter the message to encrypt: ")
num_rails = 3
ciphertext = rail_fence_cipher(text, num_rails)
print(ciphertext)

We will be happy to hear your thoughts

Leave a reply

Python and Excel Projects for practice
Register New Account
Shopping cart