Recent Posts

Code C#: Mã hóa cổ điển Rail-Fence (Rail Fence Cipher)

-

(RAIL FENCE CIPHER)
///MÃ HÓA
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;
}
///GIẢI MÃ
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);

}
///CHƯƠNG TRÌNH CHÍNH
static void Main(string[] args)
{
    int key = 4;
    string plainText = "I Made Ronaldo";

    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);

}
Tag: C, C++, C#, mã hóa cổ điển, Rail-Fence, Rail-Fence Cipher, an toàn, bảo mật




Klik untuk melihat kode: :) =( :s :D :-D ^:D ^o^ 7:( :Q :p T_T @@, :-a :W *fck* x@