Hubbry Logo
search
logo
2086039

Rail fence cipher

logo
Community Hub0 Subscribers
Read side by side
from Wikipedia
Rail fence

The rail fence cipher (also called a zigzag cipher) is a classical type of transposition cipher. It derives its name from the manner in which encryption is performed, in analogy to a fence built with horizontal rails.

Encryption

[edit]

In the rail fence cipher, the plaintext is written downwards diagonally on successive "rails" of an imaginary fence, then moving up when the bottom rail is reached, down again when the top rail is reached, and so on until the whole plaintext is written out. The ciphertext is then read off in rows.

For example, to encrypt the message 'WE ARE DISCOVERED. RUN AT ONCE.' with 3 "rails", write the text as:

W . . . E . . . C . . . R . . . U . . . O . . . 
. E . R . D . S . O . E . E . R . N . T . N . E 
. . A . . . I . . . V . . . D . . . A . . . C . 

(Spaces and punctuation are omitted.) Then read off the text horizontally to get the ciphertext:

WECRUO ERDSOEERNTNE AIVDAC

Decryption

[edit]

Let be the number of rails used during encryption. Observe that as the plaintext is written, the sequence of each letter's vertical position on the rails varies up and down in a repeating cycle. In the above example (where ) the vertical position repeats with a period of 4. In general the sequence repeats with a period of .

Let be the length of the string to be decrypted. Suppose for a moment that is a multiple of and let . One begins by splitting the ciphertext into strings such that the length of the first and last string is and the length of each intermediate string is . For the above example with , we have , so we split the ciphertext as follows:

WECRUO ERDSOEERNTNE AIVDAC

Write each string on a separate line with spaces after each letter in the first and last line:

W   E   C   R   U   O
 E R D S O E E R N T N E
  A   I   V   D   A   C

Then one can read off the plaintext down the first column, diagonally up, down the next column, and so on.

If is not a multiple of , the determination of how to split up the ciphertext is slightly more complicated than as described above, but the basic approach is the same. Alternatively, for simplicity in decrypting, one can pad the plaintext with extra letters to make its length a multiple of .


If the ciphertext has not been padded, but you either know or are willing to brute-force the number of rails used, you can decrypt it using the following steps.

As above, let be the length of the string to be decrypted and let be the number of rails used during encryption. We will add two variables, and , where = the number of diagonals in the decrypted Rail Fence, and = the number of empty spaces in the last diagonal.

Next solve for and algebraically, where both values are the smallest number possible. This is easily done by incrementing by 1 until the denominator is larger than , and then simply solving for . Consider the example cipher, modified to use 6 rails instead of 3.

W.........V.........O
.E.......O.E.......T.N
..A.....C...R.....A...C
...R...S.....E...N.....E
....E.I.......D.U.......
.....D.........R........

The resulting cipher text is:

WVO EOETN ACRAC RSENE EIDU DR

We know that , and if we use we can solve the equation above.

Simplify the fraction.

Solve for

Solve for

We now have , , and . Or, 6 rails, 5 diagonals (4+1), and 2 empty spaces at the end. By blocking out the empty spaces at the end of the last diagonal, we can simply fill in the Rail Fence line by line using the ciphertext.

_         _         _
 _       _ _       _ _
  _     _   _     _   _
   _   _     _   _     _
    _ _       _ _       X
     _         _         X
W         V         O
 E       O E       T N
  A     C   R     A   C
   _   _     _   _     _
    _ _       _ _       X
     _         _         X

Cryptanalysis

[edit]

The cipher's key is , the number of rails. If is known, the ciphertext can be decrypted by using the above algorithm. Values of equal to or greater than , the length of the ciphertext, are not usable, since then the ciphertext is the same as the plaintext. Therefore the number of usable keys is low, allowing the brute-force attack of trying all possible keys. As a result, the rail-fence cipher is considered weak.[citation needed]

Zigzag cipher

[edit]

The term zigzag cipher may refer to the rail fence cipher as described above. However, it may also refer to a different type of cipher described by Fletcher Pratt in Secret and Urgent. It is "written by ruling a sheet of paper in vertical columns, with a letter at the head of each column. A dot is made for each letter of the message in the proper column, reading from top to bottom of the sheet. The letters at the head of the columns are then cut off, the ruling erased and the message of dots sent along to the recipient, who, knowing the width of the columns and the arrangement of the letters at the top, reconstitutes the diagram and reads what it has to say."[1]

See also

[edit]

References

[edit]
[edit]
Revisions and contributorsEdit on WikipediaRead on Wikipedia
from Grokipedia
The Rail Fence cipher, also known as the zigzag cipher, is a classical transposition cipher that rearranges the letters of a plaintext message in a zigzag pattern across a predetermined number of "rails" (rows) before reading them off sequentially by row to form the ciphertext.[1] The key to the cipher is the number of rails, typically ranging from 2 to around 20, which determines the depth of the zigzag and thus the permutation of the letters.[2] For encryption, the plaintext is written diagonally downward to the bottom rail, then upward to the top, repeating this pattern until all letters are placed, after which the rows are concatenated in order.[3] Decryption reverses this process by reconstructing the zigzag grid based on the key and the ciphertext length, distributing letters into the rails and then reading diagonally to recover the original message.[1] For instance, with 3 rails and the plaintext "send more troops," the ciphertext is "SMTPEDOEROSNRO" when read by rows.[3] This method preserves letter frequencies but disrupts their order, making it a form of permutation-based encryption without substitution.[2] The origins of transposition ciphers like the Rail Fence trace back to ancient Greece, where the Spartans employed a scytale—a cylinder wrapped with a strip of parchment—to rearrange messages, with the cylinder's diameter serving as the key.[1] While the specific rail-based variant emerged later in cryptographic history, it shares this lineage as one of the earliest mechanical aids to obfuscation, predating more complex systems.[1] Due to its simplicity, the cipher is vulnerable to cryptanalysis through brute-force testing of possible rail numbers and recognition of predictable patterns, and is rarely used in modern secure communications but remains valuable for educational purposes in teaching basic cryptography principles.[1]

History

Origins

The rail fence cipher traces its roots to ancient Greek cryptography, with possible connections to Spartan military communications during the 5th century BCE. The Spartans employed the scytale, a cylindrical device for transposition that rearranged message letters by wrapping a strip of parchment around it, marking an early form of positional scrambling in secure signaling.[4] While the scytale relied on a physical tool to achieve columnar transposition, the rail fence cipher represents an evolution toward tool-free methods using a zigzag pattern across conceptual "rails," adapting similar principles of letter rearrangement for secrecy in field operations.[1] This progression from mechanical aids like the scytale highlights the development of transposition techniques in classical antiquity, where the focus was on simple, reversible disruptions of plaintext order to protect military dispatches without substituting letters. The rail fence's rail-based zigzag obscures the original sequence in a portable manner suitable for messengers.[5] The exact origins of the specific rail fence variant remain uncertain, though it evolved from ancient transposition methods and earliest accounts illustrate how Greek engineers refined such techniques for defensive signaling, laying groundwork for later adaptations. Such methods persisted and evolved into medieval variants by the early centuries CE.

Historical Usage

The rail fence cipher, a straightforward transposition technique, is said to have been employed during the Middle Ages (prior to the 15th century) as a basic method for obscuring messages in European manuscripts and military dispatches, leveraging its ease of manual application without requiring complex tools.[6] Evidence of its application in early modern espionage remains limited, but the cipher's simplicity made it suitable for non-expert users in covert operations; for instance, during the American Civil War (1861–1865), both Union and Confederate spies and field operatives utilized it to encode messages concerning troop movements, supplies, and intelligence, often in handwritten dispatches to evade interception.[7][8][9]

Description

Basic Principles

The rail fence cipher is a manual symmetric transposition cipher that rearranges the letters of the plaintext in a zigzag pattern across a predetermined number of "rails" to obscure the original message order.[10][11] This technique, also known as the zigzag cipher, relies on the physical or conceptual alignment of letters in rows resembling fence rails, providing a simple method for transposition without altering the alphabet.[12] The core mechanism involves writing the plaintext diagonally downward across the rails and then upward to the next rail, creating a patterned distribution of letters that disrupts sequential readability.[1] The resulting ciphertext is formed by concatenating the letters from each rail in horizontal order, effectively permuting the positions while preserving the original characters.[13] In contrast to substitution ciphers, which replace individual letters or symbols with others to encode the message, the rail fence cipher maintains the integrity of each letter and solely reorders their sequence for security.[14] This positional shuffling forms the basis of its transposition nature, distinguishing it as a permutation-based encryption rather than a replacement-based one.[15] The primary key parameter is the number of rails, which controls the complexity and pattern depth of the rearrangement.[16]

Parameters and Key

The primary key in the rail fence cipher is the integer $ N $, which specifies the number of rails or rows across which the plaintext is written in a zigzag pattern.[17][1] This parameter determines the depth of the transposition grid and directly influences the degree of letter rearrangement.[18] The value of $ N $ is typically kept small, often between 3 and 10, to enable practical manual encryption and decryption by hand without requiring computational tools.[19] Larger values increase complexity but also the risk of errors in the transposition process during manual application.[20] The length of the plaintext $ L $ interacts with $ N $ to shape the encryption pattern, as the zigzag traversal follows a repeating cycle with a period of $ 2(N-1) $ positions: $ N-1 $ steps downward followed by $ N-1 $ steps upward.[21] If $ L $ is not a multiple of this period, the final cycle remains incomplete, resulting in partial rails where only some positions are filled with letters, and the remaining spots are left empty.[1] This handling ensures the cipher accommodates messages of arbitrary length without padding, though it introduces minor irregularities in the transposition for shorter texts.[22]

Encryption

Procedure

The rail fence cipher encryption involves writing the plaintext message in a zigzag pattern diagonally across a fixed number of rails NN, then reading the letters row by row to produce the ciphertext. The key is the number of rails NN, typically small (e.g., 3 to 10).[23] To encrypt, first remove any spaces or punctuation from the plaintext and convert to uppercase if desired. Then, create NN empty rails (rows). Fill the rails by placing letters sequentially in a zigzag path: start at the top rail (rail 0) and move downward diagonally to the bottom rail (N1N-1), then upward diagonally back to the top, repeating this pattern until all letters are placed. The direction changes at the top and bottom rails. The positions follow a repeating cycle of length 2(N1)2(N-1): for the downward phase, rails 0 to N1N-1, then upward N2N-2 to 0. Once filled, the ciphertext is formed by concatenating the letters from each rail in order, from rail 0 to rail N1N-1, reading left to right. This transposes the positions while preserving letter order within rails.[24]

Example

Consider the plaintext "WE ARE DISCOVERED FLEE AT ONCE" with 3 rails. First, remove spaces and punctuation to get "WEAREDISCOVEREDFLEEATONCE" (length 22). The letters are placed in the zigzag pattern as follows:
  • Rail 0: W E C R L T
  • Rail 1: E R D S O E E F E A O
  • Rail 2: A I V D E
The filling order starts downward: W (rail 0, pos1), E (1, pos2), A (2, pos3); then upward: R (1, pos4), E (0, pos5); downward: D (1, pos6), I (2, pos7), S (1, pos8), C (0, pos9), and so on until all 22 letters are placed.[23] The ciphertext is read row by row: WECRLT (rail 0) + ERDSOEEFE AO (rail 1, note: ERDSOEEFEAAO) + AIVDE (rail 2), yielding "WECRLTERDSOEEFEAAOAIVDE".

Decryption

Procedure

To decrypt a ciphertext produced by the rail fence cipher, the recipient must know the number of rails NN and the length LL of the ciphertext, which equals the length of the original plaintext. The process reverses the transposition by first apportioning the ciphertext letters to the appropriate rails based on their calculated lengths, then reconstructing the plaintext by traversing the rails in the original zigzag order. The procedure begins by computing the total positions LL and the period of the zigzag pattern P=2(N1)P = 2(N-1), which represents the number of positions in one full down-and-up cycle across the rails. The number of full cycles is then K=L/PK = \lfloor L / P \rfloor, with the remainder r=LmodPr = L \mod P accounting for any incomplete cycle at the end.[22] Next, the lengths of each rail are determined by calculating the contributions from the full cycles plus the partial contributions from the remainder. In each full cycle, the top rail (rail 0) and bottom rail (rail N1N-1) each receive 1 letter, while each of the N2N-2 middle rails receives 2 letters. Thus, the base lengths are KK for the top and bottom rails and 2K2K for each middle rail. For the remainder rr, letters are added sequentially following the zigzag path: first downward through the rails starting from rail 0, adding 1 to each until the bottom, then upward from rail N2N-2 toward rail 0 until rr positions are filled.[23] The ciphertext is then distributed into the rails according to these computed lengths: the first segment of length equal to the top rail's length goes to rail 0, the next to rail 1, and so on through rail N1N-1. For instance, with N=3N=3 and L=18L=18, the top and bottom rails each receive 5 and 4 letters respectively, while the middle rail receives 9 letters.[22] Finally, the plaintext is reconstructed by reading the letters diagonally along the zigzag path: start at the first letter of rail 0 and proceed downward to rail N1N-1, then upward to rail 0, repeating this pattern while taking the next unused letter from the current rail until all letters are exhausted. This traversal follows the exact inverse of the encryption order, yielding the original message.[1]

Example

To illustrate the decryption procedure for the rail fence cipher with 3 rails, consider the ciphertext "WECRLTERDSOEEFEAOAIVDE", which has a length $ L = 22 $.[25] The period $ P $ for $ N = 3 $ rails is $ P = 2 \times (N - 1) = 4 $. The number of full cycles is $ K = \lfloor 22 / 4 \rfloor = 5 $, with a remainder of 2 letters. In each full cycle, rail 1 (top) and rail 3 (bottom) receive 1 letter each, while rail 2 (middle) receives 2 letters, yielding base lengths of 5 letters for rails 1 and 3, and 10 letters for rail 2. The remainder assigns 1 additional letter to rail 1 and 1 to rail 2, for adjusted lengths of 6 letters for rail 1, 11 for rail 2, and 5 for rail 3.[25] The ciphertext is distributed sequentially into the rails based on these lengths: rail 1 receives the first 6 letters ("WECRLT"), rail 2 the next 11 letters ("ERDSOEEFEAO"), and rail 3 the remaining 5 letters ("AIVDE").[25] The filled rails are as follows (showing the zigzag positions):
  • Rail 1: W . . . E . . . C . . . R . . . L . . . T
  • Rail 2: . E . R . D . S . O . E . E . F . E . A . O
  • Rail 3: . . A . . . I . . . V . . . D . . . E
Reading the letters in the zigzag order—alternating downward and upward across the rails—reconstructs the plaintext "WEAREDISCOVEREDFLEEATONCE".[25]

Cryptanalysis

Weaknesses

The rail fence cipher suffers from an extremely limited key space, as the key consists solely of the number of rails NN, which is typically constrained to small integer values between 2 and roughly half the message length LL to ensure meaningful transposition. For a typical message of length 50–100 characters, this results in only 10–20 possible keys to test via brute force, rendering exhaustive search feasible even manually.[10][26] As a transposition cipher, the rail fence method merely rearranges the positions of plaintext letters without altering their identities, thereby preserving the original frequency distribution of individual letters and common digrams in the ciphertext. This invariance allows attackers to apply standard frequency analysis techniques, such as identifying common letters like 'E' or 'T' in English text, to infer probable alignments despite the permuted order.[8] The ciphertext produced by the rail fence cipher often exhibits discernible visual or structural patterns, particularly through the uneven lengths of the rail segments when the message length LL is not evenly divisible by the period 2(N1)2(N-1). These segment lengths indirectly disclose information about NN, as the first and last rails are shorter than the middle ones, enabling an observer to estimate the key by examining the segmentation without decryption.[27]

Attack Methods

The rail fence cipher is vulnerable to brute-force attacks due to its limited key space, typically consisting of the number of rails NN, which is often small (e.g., 2 to 10 for practical messages).[28] An attacker can systematically test each possible NN by attempting to decrypt the ciphertext, rearranging the letters into rails and reading them diagonally until the output forms coherent plaintext.[22] This exhaustive search is feasible because the number of trials is bounded by the ciphertext length, and for messages longer than a few dozen characters, manual or computational verification quickly identifies the correct key through readability.[8] Frequency analysis can be adapted to the rail fence cipher by examining the preserved overall letter frequencies and certain bigram or trigram patterns that span across rails. Since transposition ciphers like the rail fence do not alter letter frequencies, the ciphertext exhibits the same single-letter distribution as English (e.g., high occurrences of 'E' and 'T'), confirming a transposition and guiding NN estimation.[8] Additionally, common bigrams such as "TH" or "HE" may appear intact if they fall within the same rail or adjacent diagonals, allowing an attacker to infer rail boundaries by aligning probable patterns in the ciphertext.[29] For longer texts, higher-order n-grams (e.g., quadgrams) can score potential decryptions for "English-likeness," prioritizing those with statistical profiles matching natural language.[22] In a known-plaintext attack, partial plaintext (e.g., guessed common phrases like "THE" or standard headers) enables deduction of the rail structure. The attacker maps the known plaintext positions to the ciphertext, computing the diagonal paths to reverse-engineer NN and the full permutation, then reconstructs the remaining message.[22] This method is particularly effective against the rail fence's periodic pattern, as even short matching segments reveal the rail count and offset.[28] Anagramming the rails involves segmenting the ciphertext into possible row lengths based on hypothesized NN and rearranging segments to form diagonal readings that yield sensible text. The attacker divides the ciphertext into groups corresponding to rail fillings (down and up strokes), then iteratively permutes and concatenates them until coherent words emerge, often aided by partial frequency matches or trial alignments.[28] This technique exploits the cipher's reversible transposition, succeeding with moderate ciphertext lengths where exhaustive permutations remain manageable.[22]

Zigzag Cipher

The zigzag cipher is frequently regarded as synonymous with the rail fence cipher, a classical transposition method, though it occasionally denotes a specific variant outlined in cryptographic literature. This variant, detailed by Fletcher Pratt in his 1939 book Secret and Urgent: The Story of Codes and Ciphers, employs a columnar arrangement for transposition. To encrypt, a sheet of paper is ruled into vertical columns, with the number of columns matching the key value; each column is headed by a letter from the key. Dots are then positioned along a zigzag path: descending the first column, traversing horizontally across the bottom to the second column, ascending the second, and continuing alternately. The plaintext letters are inscribed sequentially on these dots, after which the ciphertext is obtained by reading the filled columns downward in order. Decryption reverses this process by reconstructing the zigzag pattern on the dots and extracting letters column by column to restore the original message. While the zigzag variant emphasizes a vertical, columnar layout with explicit dot markers for the path—contrasting the rail fence's horizontal "rails"—both achieve mechanically similar results through periodic transposition of message positions.

Scytale Comparison

The scytale, an ancient cryptographic device attributed to Spartan military use around the 5th century BCE, functions as a physical transposition tool. It consists of a narrow strip of parchment or leather wrapped helically around a cylindrical baton of fixed diameter, upon which the plaintext message is inscribed longitudinally along the exposed surface. Once the strip is unwrapped, the characters form a seemingly random sequence that serves as the ciphertext, readable only by rewrapping the strip around a baton of identical dimensions.[12][30] Both the scytale and the rail fence cipher exemplify transposition ciphers, where security derives from the geometric rearrangement of plaintext letters rather than substitution. They share the principle of exploiting spatial patterns to permute positions, rendering the message unintelligible without knowledge of the transposition key—the baton's diameter for the scytale and the number of rails for the rail fence. The rail fence can be viewed as a conceptual evolution of the scytale, adapting its transposition logic to a flat, paper-based medium without the need for specialized hardware, thus making it more accessible for non-military applications.[12][30] Key differences lie in their transposition geometries and implementation. The scytale produces a linear or columnar rearrangement determined by the baton's circumference, resulting in a straightforward wrapping pattern, whereas the rail fence employs a diagonal zigzag traversal across multiple "rails," creating a more visually complex permutation. While the scytale's physical baton acts as a tangible key, demanding precise replication for decryption and thereby enhancing security against interception for short messages, the rail fence relies on a numerical parameter (N rails) that is easier to guess or brute-force in longer texts. The scytale's origins trace to ancient Greek transpositions for secure military signaling.[12][30]
User Avatar
No comments yet.