The rail fence cipher (also called a zigzag cipher) is a form of transposition cipher. It derives its name from the way in which it is encoded.
In the rail fence cipher, the plain text is written downwards and diagonally on successive "rails" of an imaginary fence, then moving up when we reach the bottom rail. When we reach the top rail, the message is written downwards again until the whole plaintext is written out. The message is then read off in rows. For example, if we have 3 "rails" and a message of 'WE ARE DISCOVERED. FLEE AT ONCE', the cipherer writes out:
Then reads off to get the ciphertext:
Note that this particular example does NOT use spaces separating the words. The decipherer will need to add them based on context. If spaces are shown in the ciphertext, then they must be included in the count of letters to determine the width of the solution grid.
Let's use another example to see how to actually solve a Rail Fence cipher. We'll use a 3-rail fence to encode a new phrase and include spacing in between the words. Our ciphertext comes out as IA_EZS_ELYLK_UZERLIPL. Note that our ciphertext has a total of 21 units (letters + spaces). This will be important later on as we try to decipher it.
To solve the cipher, you must know the height and cycle of the puzzle. The height is simply the number of fence rails used to create it. In this example we said that 3 fence rails were used, so our height is 3.
To determine the puzzle width, which will tell us how many total units will be in each row, you must determine the "cycle" of letters. A "cycle" of letters runs from the top row, down through each subsequent row, and then up again, but stopping before reaching the top row again. (The next letter on the top row will actually begin the next cycle.) So a 2-rail puzzle has a "cycle" of 2 units; a 3-rail puzzle has a "cycle" of 4 letters; a 4-rail puzzle has a "cycle" of 6 letters; etc. (See below.) The math equation for this is: "Cycle" = ([# of rails] x 2) - 2 (since the top and bottom rows have half as many units per cycle as any middle row(s)).
Our 3-rail fence example has a "cycle" of 4 units. So divide the total units (letters + spaces) by the cycle number and round down to the next whole number. There are 21 units in our example, so our "base puzzle width" is 5 (21 / 4 = 5.25, which rounds down to 5). It's important to realize that we actually have 5 "full cycles" plus a "partial cycle" of 1 more letter (5 x 4 = 20 and 20 + 1 = 21 units). Therefore the top row has 6 units in it (5 "full cycles" + the 1 extra letter that is starting off the 6th cycle all by itself). The middle row has 10 units (5 "full cycles" x 2 units for each cycle). The bottom row has 5 units (5 "full cycles" x 1 unit for each cycle since it's the bottom-most row).
Take the first 6 units from our ciphertext and write them across the top row, leaving much space between the units: [IA_EZS]_ELYLK_UZERLIPL.