All operations

Rail fence cipher

Write the message in a zigzag across several rails, then read off one rail at a time.

The zigzag

Characters are laid out diagonally down and back up a set of rails, then the rails are read top to bottom and joined. On three rails the first character sits on rail one, the second on rail two, the third on rail three, the fourth back on rail two, and the pattern repeats every four characters. With more rails the cycle is twice the rail count, minus two.

Rails run from 2 to 20 here, and the starting offset, 0 to 40, wraps at the cycle length and drops the first character partway into it, so a message can begin on any rail and heading in either direction.

Loaded above is the textbook example, WE ARE DISCOVERED FLEE AT ONCE stripped to letters and laid on three rails, which comes out as WECRLTEERDSOEEFEAOCAIVDEN.

A pure transposition

Every character that went in comes out. Only the order changed. A letter count of the ciphertext is a letter count of the plaintext, exact to the last E, so the statistic that breaks every simple substitution cipher tells an analyst nothing here.

That is also the diagnostic. Ciphertext whose letter distribution looks like ordinary English while none of the words are readable has been transposed rather than substituted, and the search narrows immediately.

What the key is worth

The rail count is the whole key in practice. Nineteen values, tried in sequence, and a dictionary check finds English on the right one. Bringing the offset in raises that to 380 distinct settings across the full range this tool allows, which a browser exhausts inside a single keystroke. Length gives no protection either, since a longer message only makes the correct reading more obvious.

Where it earns its place

Underneath something else. Substitution ciphers leak through adjacency: TH, HE, doubled letters and repeated trigrams keep their shape through any fixed letter mapping and hand the analyst a foothold. Transposing the substituted text pulls those pairs apart, so the digraph counts an attacker wants no longer sit next to each other. ADFGX is that idea taken seriously, fractionating with a Polybius square before a columnar transposition. Rail fence makes the same move with a pencil.

This implementation moves every character, spaces included, which clutters the output without protecting anything. Strip the message to letters first, which is how the example above is loaded.

Alphabetical substitution changes what each letter is and leaves the order alone, which is the opposite trade. ADFGX makes both moves at once and was fielded in war. Reverse is the simplest transposition there is.