> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/cis/practical-2-rail-fence-cipher-transposition-technique.md).

# Practical 2 — Rail Fence Cipher (Transposition Technique)

### Aim

To implement the Rail Fence Cipher, a classical transposition cipher, for encrypting text using Python.

### Concept

Unlike a substitution cipher (which changes *what* each character is), a **transposition cipher** changes *where* each character sits — the letters themselves are never altered, only their order is rearranged.

The classic **Rail Fence Cipher** writes the plaintext in a zigzag pattern across a number of "rails" (rows), then reads off the letters row by row to produce the ciphertext. For example, writing `HELLO WORLD` across 3 rails in a zigzag and reading row-by-row scrambles the letter order while keeping every original letter intact.

The version implemented in this practical is a **simplified 2-rail variant**: instead of a zigzag, it splits the text into characters at **even index positions** and characters at **odd index positions**, then concatenates the even group followed by the odd group. This is equivalent to writing the text along two straight rails (rail 0 takes every 2nd character starting at position 0, rail 1 takes every 2nd character starting at position 1) rather than a zigzag — a simpler, 2-row form of the same rail-based transposition idea.

### Mathematical / Logical Formula

For a string of length `n`, indexed from `0` to `n-1`:

```
Rail 0 (evens) = characters at indices 0, 2, 4, 6, ...
Rail 1 (odds)  = characters at indices 1, 3, 5, 7, ...

Ciphertext = Rail 0 + Rail 1   (concatenated)
```

In set notation, for index `i` from `0` to `n-1`:

```
Evens = { text[i] : i mod 2 = 0 }
Odds  = { text[i] : i mod 2 = 1 }
Ciphertext = Evens ⧺ Odds
```

(`⧺` denotes string concatenation.)

### Python Code

```python
def rail_fence_encrypt(text):
    evens = ''.join([text[i] for i in range(0, len(text), 2)])
    odds = ''.join([text[i] for i in range(1, len(text), 2)])
    return evens + odds

num = int(input("Enter the amount of names to cipher"))
message = [0] * num
for name in range(len(message)):
    message[name] = input(f"Name {name+1}:")
for name in range(len(message)):
    print("Original: ", message[name])
    print("Rail Fence (Transposition): ", rail_fence_encrypt(message[name]))
```

### Line-by-Line Explanation

#### The `rail_fence_encrypt` function

```python
def rail_fence_encrypt(text):
```

Defines a function `rail_fence_encrypt` that takes one parameter, `text` — the string to be transposed/encrypted.

```python
    evens = ''.join([text[i] for i in range(0, len(text), 2)])
```

This line builds the string of "even-indexed" characters:

* `range(0, len(text), 2)` generates indices `0, 2, 4, 6, ...` up to (but not including) `len(text)` — i.e. it starts at `0` and steps by `2` each time, which selects every character at an even position.
* `[text[i] for i in ...]` is a **list comprehension**: for each such index `i`, it grabs the character `text[i]` and collects all of them into a list.
* `''.join([...])` takes that list of individual characters and joins them together into a single string with no separator between them.
* The final joined string is stored in the variable `evens`.

```python
    odds = ''.join([text[i] for i in range(1, len(text), 2)])
```

Same idea as above, but `range(1, len(text), 2)` starts at index `1` instead of `0`, so it generates `1, 3, 5, 7, ...` — every character at an **odd** position. These are joined into the string `odds`.

```python
    return evens + odds
```

Concatenates the `evens` string and the `odds` string (evens first, then odds) and returns this combined string as the final ciphertext. This is what actually scrambles the order — all the even-position characters now appear first, followed by all the odd-position characters, which is a different order than the original text.

#### The main program

```python
num = int(input("Enter the amount of names to cipher"))
```

Asks the user how many names/messages they want to process, and converts the typed input (a string) into an integer.

```python
message = [0] * num
```

Creates a list of length `num`, with every element initially set to `0` as a placeholder, ready to hold the actual names.

```python
for name in range(len(message)):
    message[name] = input(f"Name {name+1}:")
```

Loops through each index in `message` and prompts the user to type a name for that slot (the prompt numbers the names starting from 1 for readability, even though the underlying index starts at 0). Each entered name overwrites the placeholder `0`.

```python
for name in range(len(message)):
    print("Original: ", message[name])
    print("Rail Fence (Transposition): ", rail_fence_encrypt(message[name]))
```

Loops through all the stored names again. For each name it:

* Prints the original (unmodified) name.
* Calls `rail_fence_encrypt()` on that name and prints the resulting transposed ciphertext.

### Sample Output

```
Enter the amount of names to cipher: 1
Name 1: HELLO
Original:  HELLO
Rail Fence (Transposition):  HLOEL
```

Walkthrough for `"HELLO"` (indices 0=H, 1=E, 2=L, 3=L, 4=O):

* Evens (indices 0, 2, 4) → `H`, `L`, `O` → `"HLO"`
* Odds (indices 1, 3) → `E`, `L` → `"EL"`
* Result: `"HLO" + "EL"` = `"HLOEL"`

### Conclusion

The Rail Fence Cipher shows how a transposition technique can obscure a message purely by rearranging character positions, without changing any of the characters themselves — the opposite approach to substitution ciphers like the Caesar Cipher.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/cis/practical-2-rail-fence-cipher-transposition-technique.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
