Resource · Guide or article
Rail Fence Cipher
Covers the rail fence, or zigzag, transposition cipher: characters run diagonally down and up across rails and are read off rail by rail.
Reviewed
Open the original: Rail Fence Cipher (opens the original site in a new tab)Add to a roadmap
Keep this resource with a roadmap you follow. It appears as your own extra resource; the roadmap's steps don't change and it doesn't count toward your tracked steps.
Source content: English
The rail fence cipher (also called a zigzag cipher) is a transposition cipher in which the message is split across a set of rails on a fence for encoding. The fence is populated with the message's characters, starting at the top left and adding a character on each position, traversing them diagonally to the bottom. Upon reaching the last rail, the direction should then turn diagonal and upwards up to the very first rail in a zig-zag motion. Rinse and repeat until the message is fully disposed across the fence. The encoded message is the result of concatenating the text in each rail, from top to bottom. From wikipedia, this is what the message WE ARE DISCOVERED. FLEE AT ONCE looks like on a 3-rail fence: The message can then be decoded by re-creating the encoded fence, with the same traversal pattern, except characters should only be added on one rail at a time. To illustrate that, a dash can be added on the rails that are not supposed to be populated yet. This is what the fence would look like after populating the first rail, the dashes represent positions that were visited but not populated.
PrepKit overview
PrepKit editors wrote and reviewed this overview from the source repository. It is not text from the resource itself.
- Suited to
- The source does not state a level
- Format
- Reference
What it covers
- Three-rail encoding of WE ARE DISCOVERED. FLEE AT ONCE drawn as a text grid, with the resulting ciphertext
- Decoding by replaying the zigzag and filling one rail at a time, using dashes for visited but empty positions
- When to start filling the next rail during decoding
How to use it
PrepKit study advice, not a claim made by the source.
Code encode and decode for any rail count and confirm that decoding the three-rail ciphertext restores the message.
Scope and limitations
No complexity figures or code in the README; outside reading is a Wikipedia page and an online calculator.
Access and format
Free English README on GitHub in the MIT-licensed trekhleb/javascript-algorithms repository.
Reviewed by PrepKit on Oct 2, 2026. Listing source commit: 85293e3e2b88
Evidence behind this overview
- src/algorithms/cryptography/rail-fence-cipher/README.md
Pages that include this
Get the PrepKit newsletter
Optional. You don't need it to use PrepKit.