What is the Rail Fence cipher?
The Rail Fence is a transposition cipher: it doesn’t change letters, it reorders them. The message is written in a zig-zag pattern across n rails (rows) and then read row by row to form the ciphertext.
This zig-zag has a period of 2·(n−1) characters (for n ≥ 2).
When n = 1 the message is unchanged (identity). When n = 2, the result
is simply the interleaving of alternating rows.
How it works
1) Choose n rails (n ≥ 2): this sets the number of rows for the pattern.
2) Write in zig-zag: move diagonally down to the bottom rail, then up to the top rail, repeating. Place each letter of the (normalized) text at the corresponding position along this path.
3) Read by rows: concatenate the rows from top to bottom to obtain the ciphertext.
Decryption: rebuild the zig-zag skeleton using the same rail count, mark the positions row by row with the ciphertext, then read along the zig-zag to recover the plaintext.
Example
Plaintext: ATAQUEAMANECER • Rails: 3
Write the text in zig-zag (down to rail 3, up to rail 1, repeat), then read row by row.
Basic layout
Plaintext: ATAQUEAMANECER Rails: 3 Pattern: (go down to the last rail, then up, repeat) A . . . U . . . A . . . E . . T . Q . E . M . N . C . R . . A . . . A . . . E . . . Cipher: AUAETQEMNCRAAE
Normalize accents for the pattern (á→a, etc.). In a didactic mode you may choose to
preserve special letters (e.g., ñ/Ñ) and document that decision.
History
- Clear, modern illustration of transposition, widely used in teaching and outreach.
- Common in recreational mathematics, logic challenges, and school competitions thanks to its visual pattern.
Classic attacks
- Rail enumeration: try different values of
nand rebuild the zig-zag. - Language heuristics: validate candidates with frequent bigrams/trigrams and likely words.
- Period exploitation: use the period
2·(n−1)to narrow the search quickly.
As with any transposition, overall letter frequencies are preserved; only the order changes, which helps identify the method.
Pros and cons
Pros
- Highly visual and didactic for understanding transpositions and periodic patterns.
- Single, intuitive parameter (
nrails) for experimentation. - Easy to implement and reproduce using a matrix or direct indexing.
Cons
- Simple transposition: with enough text, both the pattern and
nare easy to recover. - Sensitive to normalization choices (spaces/punctuation); document them for decryption.
- Provides no integrity or authenticity; it only reorders the message.