---
title: "Rail fence"
description: "Write the text in a zigzag over N rails, read the rails one after another. A transposition, so the letters never change."
canonical_url: "https://ciphers.agntn.dev/ciphers/rail-fence"
---
# Rail fence

> Write the text in a zigzag over N rails, read the rails one after another. A transposition, so the letters never change.

<cipher-facts name="rail-fence">



</cipher-facts>

The text goes down and up across `rails` lines and is read off one line at a time. Nothing is substituted, so the histogram of the output is the histogram of the input. Every character counts, spaces included. When the puzzle stripped them first, `stripNonAlpha: true` does the same, and `preserveCase: false` uppercases the result. `rails` is at least 2, default 3.

```ts
const railFence = create("rail-fence");
railFence.encode("WEAREDISCOVEREDRUNATONCE", { rails: 3 }).text; // "WECRUOERDSOEERNTNEAIVDAC"
railFence.decode("WECRUOERDSOEERNTNEAIVDAC", { rails: 3 }).text; // "WEAREDISCOVEREDRUNATONCE"
railFence.encode("WE ARE DISCOVERED. RUN AT ONCE.", { rails: 3, stripNonAlpha: true }).text; // same ciphertext
railFence.encode("HELLO", { rails: 1 }); // throws, one rail is the identity
```

Keyspace is about the length of the text. Try every rail count and read, it takes a minute.


## Sitemap

See the full [sitemap](https://ciphers.agntn.dev/sitemap.md) for all pages.
