Function Repository Resource:

RailFenceCipher

Source Notebook

Encipher a string using the rail fence cipher

Contributed by: Sander Huisman

ResourceFunction["RailFenceCipher"][string,n]

enciphers string using the rail fence cipher with n rails.

Details and Options

The value for n should be 2 or larger.
Tabs, new lines and spaces are automatically removed.
The letters ci zigzag on the n rails as follows:
The letters are then collected row by row from left to right and top to bottom.

Examples

Basic Examples (1) 

Encipher a string using the rail fence cipher on 3 rails:

In[1]:=
ResourceFunction["RailFenceCipher"]["WE ARE DISCOVERED FLEE AT ONCE",
  3]
Out[1]=

Properties and Relations (2) 

The rail fence cipher is a transposition cipher, that is, the characters are scrambled rather than replaced:

In[2]:=
str = "WEAREDISCOVEREDFLEEATONCE";
{Sort[Characters[ResourceFunction["RailFenceCipher"][str, 3]]], Sort[Characters[str]]}
Out[3]=

The first character is not moved:

In[4]:=
str = "this is just a test";
Table[{i, ResourceFunction["RailFenceCipher"][str, i]}, {i, 2, 15}] // Grid
Out[5]=

Possible Issues (2) 

If the number of rails is large compared to the length of the encoded message then a large part might be readable:

In[6]:=
ResourceFunction[
 "RailFenceCipher"]["WE ARE DISCOVERED FLEE AT ONCE", 20]
Out[6]=

Decrease the number of lines to scramble the message:

In[7]:=
ResourceFunction["RailFenceCipher"]["WE ARE DISCOVERED FLEE AT ONCE",
  8]
Out[7]=

Neat Examples (1) 

Use a varying number of rails for the same message:

In[8]:=
Grid[{#, ResourceFunction["RailFenceCipher"][
     "WE ARE DISCOVERED FLEE AT ONCE", #]} & /@ Range[2, 25]]
Out[8]=

Publisher

SHuisman

Version History

  • 1.0.0 – 31 July 2019

Related Resources

License Information