Skip to main content


Home Rail fence cipher

Rail fence cipher

(also railfence cipher)

Rail fence cipher definition

The rail fence cipher is a simple transposition cipher that encrypts plaintext by rearranging the characters in a zigzag pattern. The term “rail fence” refers to the arrangement of characters in the cipher, which resembles the rails of a fence.

The rail fence cipher should not be confused for the zigzag cipher, which is a separate cipher described by Fletcher Pratt in Secret and Urgent. The confusion is exacerbated by the fact that “zigzag cipher” is used synonymously with “rail fence cipher” in many popular sources.

See also: caesar encryption, encryption key, block cipher, ciphertext, substitution cipher, transposition cipher

How the rail fence cipher works

To encode a message, write the plaintext diagonally across the “rails” (rows) in a zigzag pattern, starting with the first character in the top-left corner. The next character continues in the row below, with each new character dropping down until the bottom row is reached. When that happens, reverse the direction — the characters should now climb up rows diagonally.

Repeat the process until the message is written. Then, scrunch up all the characters in each row together to make up nonsensical words and add those words to the ciphertext. The cipher key being the number of rows used to make the pattern.

We can illustrate how the rail cipher works with a simple example. In this case, the plaintext message is “HELLO” and the cipher key is “3.”

H…O{linebreak}.E.L.{linebreak}..L..{linebreak}{linebreak}

The resulting ciphertext would be “HO EL L.”