Rail fence cipher
Write the message in a zigzag across rails, then read each rail in turn.
- Family
- Transposition
- Era
- Used in the American Civil War
- Keys
- Number of rails (2 to message length − 1)
The rail fence cipher doesn't change any letter. It only changes their order, which makes it a transposition cipher rather than a substitution.
The message is written diagonally down and up across a number of rails, like a zigzag fence, and the ciphertext is read off one rail at a time.
01 / 9 · Inside the rail fence
A message to hide
This readable text is the plaintext; encrypting turns it into ciphertext. Letters only, spaces removed. This time no letter will be changed.
This cipher only moves letters around: watch where they go.
Playground
Write your own message on the rails
Type a message and choose the number of rails, then step through both phases: writing the zigzag and reading it back in another order.
Your input
Every character counts here, spaces included (shown as ␣).
WRIVDEAEDSOEE CR
- 1. Write the zigzag
- 2. Read rail by rail
Encrypt
Zigzag over 3 rails, then read row by row
What happens
Write the message one character per column, going down the rails and bouncing back up at the bottom. Then read the top rail left to right, then the next one, and so on: that order is the ciphertext.
On your values
cycle = 2 × (3 − 1) = 4
p = i mod 4
rail = (p < 3 ? p : 4 − p) + 1
rail lengths: 5 · 8 · 4
Why it matters
No character changes, only the order: this is a transposition. The letter counts stay those of normal language, which tells an attacker what kind of cipher it is.
Start
← → to step · space to playWrite the zigzag
How it’s broken
Try every rail count
The key is one small number: at most 17 − 1 rails make sense for 17 characters. An attacker undoes the zigzag for every count and keeps the line that reads.
- 2 railsWSROIEVED E ACERD
- 3 railsWE ARE DISCOVERED← your key
- 4 railsWVD SDREOCEAIEER
- 5 railsWVEECEDDRES R OAI
- 6 railsWIEDECESAVRDEO R
- 7 railsWIEDE RCESAVRDEO
- 8 railsWIEDOE RC ESAVRDE
- 9 railsWIDADOE RC ESEEVR
- 10 railsWRIDADOE RC ESEEV
Same letters, sorted
ACDDEEEEIORRSVW
ACDDEEEEIORRSVW
Sorted, the message and the ciphertext are identical: a transposition only moves letters, so their counts give it away at once.
How it works
- 1Choose the number of rails.
- 2Write the characters one per column, moving down a rail each time and bouncing back up at the bottom.
- 3Read the top rail from left to right, then the second rail, and so on.
- 4To decrypt, work out how many characters belong on each rail, fill the rails in order, then read the zigzag.
How it is broken
The ciphertext has exactly the letter frequencies of the plaintext, which tells a cryptanalyst that it is a transposition.
The number of rails is the only key, and it is small enough to try every value.