Rail-Fence Cipher C# Source Code

The rail-fence cipher algorithm has been posted before so this post just show how to implement the algorithm to programming language in C#. First of all always the encryption method:

public static string Encrypt(int rail, string plainText)
{
    List<string> railFence = new List<string>();
    for (int i = 0; i < rail; i++)
    {
        railFence.Add("");
    }

    int number = 0;
    int increment = 1;
    foreach (char c in plainText)
    {
        if (number + increment == rail)
        {
            increment = -1;
        }
        else if (number + increment == -1)
        {
            increment = 1;
        }
        railFence[number] += c;
        number += increment;
    }

    string buffer = "";
    foreach (string s in railFence)
    {
        buffer += s;
    }
    return buffer;
}

And the second is the decryption method. The key of rail-fence cipher is the number of rail is used. In this case use kaey / rail number is 4 like in the post which showing rail-fence algorithm.

public static string Decrypt(int rail, string cipherText)
{
    int cipherLength = cipherText.Length;
    List<List<int>> railFence = new List<List<int>>();
    for (int i = 0; i < rail; i++)
    {
        railFence.Add(new List<int>());
    }

    int number = 0;
    int increment = 1;
    for (int i = 0; i < cipherLength; i++)
    {
        if (number + increment == rail)
        {
            increment = -1;
        }
        else if (number + increment == -1)
        {
            increment = 1;
        }
        railFence[number].Add(i);
        number += increment;
    }

    int counter = 0;
    char[] buffer = new char[cipherLength];
    for (int i = 0; i < rail; i++)
    {
        for (int j = 0; j < railFence[i].Count; j++)
        {
            buffer[railFence[i][j]] = cipherText[counter];
            counter++;
        }
    }

    return new string(buffer);
}

Here’s the bonus code, the use of two method above

static void Main(string[] args)
{
    int key = 4;
    string plainText = "I Made Krisna Widhiastra";

    string cipherText   = RailFence.Encrypt(key, plainText);
    string decryptText  = RailFence.Decrypt(key, cipherText);

    Console.WriteLine("Plain Text   : " + plainText);
    Console.WriteLine("Cipher Text  : " + cipherText);
    Console.WriteLine("Decrypt Text : " + decryptText);
}

And the result of code above is:

Plain Text   : I Made Krisna Widhiastra
Cipher Text  : I ai eKn haaMdrsWdsraiit
Decrypt Text : I Made Krisna Widhiastra

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation