Skip to main content

Rail Fence Cipher

Definition​

The Rail Fence Cipher is a transposition cipher technique that rearranges the plaintext characters by writing them in a zigzag pattern across a specified number of "rails" or lines. It is a simple form of encryption that can be easily implemented

Practice​

rail_fence_cipher(plaintext, num_rails):
// Initialize an empty list for each rail
rails = []
for i from 0 to num_rails - 1:
rails.append([])

// Fill the rails with the plaintext characters
rail_num = 0
direction = 1 // Direction of the diagonal movement
for char in plaintext:
rails[rail_num].append(char)
rail_num += direction
// Change direction when reaching the first or last rail
if rail_num == 0 or rail_num == num_rails - 1:
direction = -direction

// Concatenate the characters from each rail to form the ciphertext
ciphertext = ""
for rail in rails:
ciphertext += ''.join(rail)

return ciphertext